﻿function Chicklets(id, url, title)
{
	this.container			= $('#' + id);
	this.url				= url || document.location.href;
	this.title				= title || window.title;
	
	this.emailForm			= $('.emailForm', this.container);
	this.emailLink			= $('a.emailAFriend', this.container);
	this.friendsEmailBox	= $('input[type=text]', this.container);
	this.messageBox			= $('textarea', this.container);
	this.sendButton			= $('button[type=submit]', this.container);
	this.cancelButton		= $('.closestf', this.container);
	
	this.emailLink.click(this.emailClicked.bindEventListener(this));
	this.sendButton.click(this.sendClicked.bindEventListener(this));
	this.cancelButton.click(this.cancelClicked.bindEventListener(this));
}

Chicklets.prototype = {

	getRecipients: function()
	{
		var recipients = this.friendsEmailBox.attr('value');
		if (!recipients)
			recipients = '';
		return recipients;
	},

	getMessage: function()
	{
		var msg = this.messageBox.attr('value');
		if (!msg)
			msg = '';
		return msg;
	},

	emailClicked: function(evt)
	{
		if (!Request.IsAuthenticated)
		{
			alert("Please login or register to share.");
			return false;
		}
	
		this.emailForm.toggle();
		evt.target.blur();
		return false;
	},

	sendClicked: function(evt)
	{
		if (this.isSending)
			return false;
		if (!this.validateRecipients())
			return false;
		this.isSending = true;
		$.post(Url.format("~/Handlers/RecommendPage.ashx"),
			{ recipients:this.getRecipients(), message:this.getMessage(), url:this.url, title:this.pageTitle }, this.emailSent.bind(this));
		return false;
	},

	cancelClicked: function(evt)
	{
		this.emailForm.hide();
		return false;
	},

	emailSent: function(data)
	{
		this.emailForm.hide();
		if (data == 'success')
		{
			alert("Thanks! email sent to " + this.getRecipients());
		}
		else
		{
			this.failed();
		}
		this.isSending = false;
	},
	
	failed: function()
	{
		alert("Sorry, something went wrong. Please try again later.");
	},
	
	validateRecipients: function()
	{
		if (this.getRecipients().length == 0)
		{
			alert("Please enter an email address");
			return false;
		}
		var recipients = this.getRecipients().split(',');
		for (i = 0; i < recipients.length; i++)
		{
			var r = recipients[i].trim();
			if (!this.validateEmailAddress(r))
			{
				alert(r + " is not a valid email address");
				return false;
			}
		}
		return true;
	},
	
	validateEmailAddress: function(email)
	{
		if (email.indexOf('@') == -1)
			return false;
		return true;
	}
}