﻿$(document).ready(function(){

	$('[icobalt=CobaltControls.Controls.ReferAFriend]').click(function(e){

		var link = $(this);
		var popup = link.data('popup');
		if (!popup)
		{
			var div = link.children('div:hidden');
			var html = div.html();
			div.remove();

			popup = new $.cobalt.dialog();
			popup.title = link.attr('_title')||'REFER A FRIEND';
			popup.contentHtml = html;
			popup.width = $.toInt(link.attr('_width')) || 430;
			popup.initContents = function(){
				this.main.find('input:button,input:submit,input:image')
					.data('dialog',popup)
					.data('link',link)
					.click(ReferAFriend);
			};
			popup.clearContents = function(o){
				var page = window.location.href.split('/').pop().split('?').shift();
				this.main.find('span.rf_page').html(page);
			};

			link.data('popup',popup);
		}

		popup.open({hideFooter:true});
	});

});

function ReferAFriend(e)
{
	var btn = $(this);
	var d = btn.data('dialog');
	var link = btn.data('link');
	
	// Make the button disabled
	btn.attr("disabled","disabled");
	
	// Get all the form elements
	var data = {PagePath:window.location.href.split('?').shift()};
	d.main.find('[name]').each(function(i){
	
			// Get the element.
			var input = $(this);
			var name = input.attr('name');
			
			// And its value.
			if (input.is('input:checkbox'))
				val = ''+input[0].checked;
			else if (input.is('input:radio:checked'))
				val = input.val();
			else if (input.is('table'))
			{
				val = '';
				input.find('input').each(function(i){
					val += $(this).val();
				});
			}
			else
				val = input.val();

			// If we have a value, record it.
			if(val)
				data[name] = val;
		});

	// Get the values.
	var smtpid = $.toInt(link.attr('_smtpid'));
	var url = $.getAjaxUrl('Shared/Contact/ReferAFriend.aspx',{ReferAFriend:true,SMTPID:smtpid});
	var fn = function(d,btn){
		return function(){
			btn.removeAttr('disabled');
			d.close();
			btn = null;
			d = null;
		};
	}(d,btn);
	$.ajax({url:url,type:'POST',data:data,success:fn,error:function(){alert('There was an error sending this email. Our tech team has been notified. Please try again at a later time.');}});
}