$(document).ready(function() {
	
	function isEmailAddress(CheckValue) {
		if (CheckValue)
		{
			var emailReg = '^[\\w-_\.+]*[\\w-_\.]\@([\\w]+\\.)+[\\w]+[\\w]$';
			var regexp = new RegExp(emailReg);
			if (CheckValue.match(regexp)) return true;
		}	
        return false;
    }

	function WipeCardCookies()
	{
		$.cookie('eCard_id', null);
		$.cookie('eCard_font', null);
		$.cookie('eCard_message', null);
		$.cookie('eCard_UserPreview', null);
	}
	WipeCardCookies();
	
	function eCard_SenderActivate(me)
	{
		me.val('');
		me.css('font-style', 'normal');
		me.css('color', '#000');
		me.unbind('click');
		me.unbind('focus');
		me.change(function(e){
			if(!isEmailAddress($(this).val()))
				$('#ecard_email_check').html('Invalid email address:<br />' + $(this).val());
			else
				$('#ecard_email_check').html('');
		});
			
		me.blur(function(e){
			if(!isEmailAddress($(this).val()))
				$('#ecard_email_check').html('Invalid email address:<br />' + $(this).val());
			else
			$('#ecard_email_check').html('');
		});
	}
	
	function eCard_CheckEmailList(CSVList)
	{
		var tmpList = CSVList.replace(/\s*/g, ''); //get rid of all spaces
		tmpList = tmpList.replace(/^,+|,+$/g, ''); //get rid of all leading and trailing commas
		tmpList = tmpList.replace(/,+/g, ','); //get rid of multiple commas between words
		var listArray = tmpList.split(',');
		$('#ecard_email_check').html('');
		for (var i=0; i<listArray.length; i++) 
		{
		    if(!isEmailAddress(listArray[i]))
			{
				$('#ecard_email_check').html('Invalid email address:<br />' + listArray[i]);
				return false;
			}
		}
		return true;
	}
	
	function eCard_RecipientActivate(me)
	{
		me.val('');
		me.css('font-style', 'normal');
		me.css('color', '#000');
		me.unbind('click');
		me.unbind('focus');
		me.change(function(e){
			eCard_CheckEmailList($(this).val());
		});
			
		me.blur(function(e){
			eCard_CheckEmailList($(this).val());
		});
	}
	
	function SendeCard()
	{
		var ChosenCard = $.cookie('eCard_id');
		var CardToSend = $.cookie('eCard_UserPreview');
		var SenderName = $('#eCard_sender_name').val();
		var SenderEmail = $('#eCard_sender_address').val();
		var mailingList = $('#ecard_recipients').val().replace(/\s*/g, ''); //get rid of all spaces
		mailingList = mailingList.replace(/^,+|,+$/g, ''); //get rid of all leading and trailing commas
		mailingList = mailingList.replace(/,+/g, ','); //get rid of multiple commas between words
		var SendToSender = true;
		
		var mailArray = mailingList.split(',');
		if (mailArray.length > 12)
		{
			$('#ecard_email_check').html('It seems you included ' + mailArray.length + ' email<br />addresses. The maximum is 12.');
			return;
		}
		
		
		if ($('#eCard_sender_copy:checked').val() == null) {
			SendToSender = false;
		}
		
		$('#eCardPreview_notice_shadow').remove();
		$('#eCardPreview_notice').remove();
		$('#eCardSpace').append('<div id="eCardPreview_notice_shadow"></div>');
		$('#eCardSpace').append('<div id="eCardPreview_notice"><p>We are sending your card. This will only take a moment...</p></div>');
		
		var parent_top = $('div.bottom_background').position_wSafariAuto().top + 350;
		var parent_left = $('div.bottom_background').position_wSafariAuto().left + 400;
		$('#eCardPreview_notice_shadow').css('top', parent_top + 'px');
		$('#eCardPreview_notice_shadow').css('left', parent_left + 'px');
		$('#eCardPreview_notice').css('top', (parent_top + 2) + 'px');
		$('#eCardPreview_notice').css('left', (parent_left + 2) + 'px');
		
		$.post('a_ecard_send.aspx', {CardID: ChosenCard, CardLocation: CardToSend, CardSender: SenderName, CardSenderAddress: SenderEmail, CardRecipients: mailingList, CCSender: SendToSender}, function(SendResults) {			
			if (SendResults == 'captcha_timeout')
			{
				window.location = './cards.aspx';
			}
			else
			{
				$('#eCardPreview_notice').remove();
				$('#eCardPreview_notice_shadow').remove();
				if (SendResults == 'done')
				{
					$.cookie('eCard_id', null);
					$.cookie('eCard_UserPreview', null);
					$.cookie('eCard_message', null);
					$.cookie('eCard_font', null);
					$('#backnext').hide();
					$('#eCard_work_box').remove();
					$('#eCardSpace').append('<div id="eCard_work_box"><p class="large">Thanks for sending one<br />of our ecards. Wish to<br />send another?</p><p><br/><a  class="large" href="./cards.aspx">Click here</a></p></div>');				
					var parent_top = $('div.bottom_background').position_wSafariAuto().top + 200;
					var parent_left = $('div.bottom_background').position_wSafariAuto().left + 630;
					$('#eCard_work_box').css('top', parent_top + 'px');
					$('#eCard_work_box').css('left', parent_left + 'px');
				}
				else if (SendResults == 'fail')
				{
					$('#eCardPreview_notice_shadow').remove();
					$('#eCardPreview_notice').remove();
					$('#eCardSpace').append('<div id="eCardPreview_notice_shadow"></div>');
					$('#eCardSpace').append('<div id="eCardPreview_notice"><p>It seems that we could not send your card. Please try again in a moment.</p></div>');
					var parent_top = $('div.bottom_background').position_wSafariAuto().top + 350;
					var parent_left = $('div.bottom_background').position_wSafariAuto().left + 400;
					$('#eCardPreview_notice_shadow').css('top', parent_top + 'px');
					$('#eCardPreview_notice_shadow').css('left', parent_left + 'px');
					$('#eCardPreview_notice').css('top', (parent_top + 2) + 'px');
					$('#eCardPreview_notice').css('left', (parent_left + 2) + 'px');
				}
			}
		});
	}
	
	function ShowRecipientSelection()
	{
		
		$.post('a_ecard_recipient_form.aspx', function(eCardForm) {
			// format and output result
			if(eCardForm)
			{
				//alert($.cookie('eCard_font'));
				$('#eCard_work_box').remove();
				
				$('#eCardSpace').append(eCardForm);
				
				var parent_top = $('div.bottom_background').position_wSafariAuto().top + 200;
				var parent_left = $('div.bottom_background').position_wSafariAuto().left + 640;
				$('#eCard_work_box').css('top', parent_top + 'px');
				$('#eCard_work_box').css('left', parent_left + 'px');
				
				$('#eCard_sender_address').click(function(e){
					eCard_SenderActivate($(this));
				});
				
				$('#eCard_sender_address').focus(function(e){
					eCard_SenderActivate($(this));
				});
				
				$('#eCard_sender_name').click(function(e){
					var me = $(this);
					me.val('');
					me.css('font-style', 'normal');
					me.css('color', '#000');
					me.unbind('click');
				});
				
				$('#eCard_sender_name').focus(function(e){
					var me = $(this);
					me.val('');
					me.css('font-style', 'normal');
					me.css('color', '#000');
					me.unbind('focus');
				});
				
				$('#ecard_recipients').click(function(e){
					eCard_RecipientActivate($(this));
				});
				
				$('#ecard_recipients').focus(function(e){
					eCard_RecipientActivate($(this));
				});
				
				$('#backnext').show();
				$('#backnext a').unbind('click');
				$('#buttonBack').click(function(e){
					e.preventDefault();
					ShowUserPreview();
				});
				$('#buttonNext').click(function(e){
					e.preventDefault();
					if ((eCard_CheckEmailList($('#ecard_recipients').val())) && (isEmailAddress($('#eCard_sender_address').val())) && ($('#eCard_sender_name').val().replace(/\s*/g, '').length > 0) && ($('#eCard_sender_name').val() != 'From: your name'))
					{
						SendeCard();
					}
					else
					{
						$('#ecard_email_check').html('You need to fill out all the fields<br />and make sure your email <br /> addresses are all correct.');
					}
				});
			}
		});
	}
	
	function ShowUserPreview()
	{
		var UserMessage = $.cookie('eCard_message');
		var ChosenCard = $.cookie('eCard_id');
		var ChosenFont = $.cookie('eCard_font');
		$('#buttonNext').unbind('click');
		
		$.post('a_get_ecard_user_preview.aspx', {CardID: ChosenCard, FontSelection: ChosenFont, Card_Message: UserMessage}, function(PrevieweCardLocation) {
			if (PrevieweCardLocation)
			{
				if (PrevieweCardLocation == 'captcha_timeout')
				{
					window.location = './cards.aspx';
				}
				else
				{
					var OriginalCard = $('#' + ChosenCard).attr('src');
					$('#eCard_work_box').remove();
					$('#' + ChosenCard).attr('src', PrevieweCardLocation);
					$.cookie('eCard_UserPreview', PrevieweCardLocation);
					
					$('#eCardSpace').append('<div id="eCardPreview_notice_shadow"></div>');
					$('#eCardSpace').append('<div id="eCardPreview_notice"><p>Click next to add  recipients and send this card. If you would like to revise your message, click back. </p></div>');
					
					var parent_top = $('div.bottom_background').position_wSafariAuto().top + 350;
					var parent_left = $('div.bottom_background').position_wSafariAuto().left + 400;
					$('#eCardPreview_notice_shadow').css('top', parent_top + 'px');
					$('#eCardPreview_notice_shadow').css('left', parent_left + 'px');
					$('#eCardPreview_notice').css('top', (parent_top + 2) + 'px');
					$('#eCardPreview_notice').css('left', (parent_left + 2) + 'px');
					
					$('#backnext').show();
					$('#backnext a').unbind('click');
					$('#buttonBack').click(function(e){
						e.preventDefault();
						$('#eCardPreview_notice').remove();
						$('#eCardPreview_notice_shadow').remove();
						$('#' + ChosenCard).attr('src', OriginalCard);
						$.cookie('eCard_UserPreview', null);
						ShowMessage();
					});
					$('#buttonNext').click(function(e){
						e.preventDefault();
						$('#' + ChosenCard).attr('src', OriginalCard);
						$('#eCardPreview_notice').remove();
						$('#eCardPreview_notice_shadow').remove();
						ShowRecipientSelection();
					});
				}
			}
		});
	}

	function ShowFonts()
	{
		$.post('a_ecard_fonts_form.aspx', function(eCardForm) {
			// format and output result
			if(eCardForm)
			{
				//alert($.cookie('eCard_font'));
				$('#eCard_work_box').remove();
				
				$('#eCardSpace').append(eCardForm);
				
				var parent_top = $('div.bottom_background').position_wSafariAuto().top + 200;
				var parent_left = $('div.bottom_background').position_wSafariAuto().left + 630;
				$('#eCard_work_box').css('top', parent_top + 'px');
				$('#eCard_work_box').css('left', parent_left + 'px');
				
				$('#eCard_work_box input').css('padding', '5px 0px 0px 3px');
				
				$('input[name=rFontSelector]').each(function(){
					if ($(this).val() == $.cookie('eCard_font'))
					{
						$(this).attr('checked', 'checked'); 
					}
				});
				
				
				$('#backnext').show();
				$('#backnext a').unbind('click');
				$('#buttonBack').click(function(e){
					e.preventDefault();
					$.cookie('eCard_font', $('input[name=rFontSelector]:checked').val());
					ShowPreviews();
				});
				$('#buttonNext').click(function(e){
					e.preventDefault();
					$.cookie('eCard_font', $('input[name=rFontSelector]:checked').val());
					ShowMessage();
				});
			}
		});
	}
	
	function eCardMessageBoxActivate(NewMessageValue)
	{
		var textareaMessage = $('#ecard_text');
		textareaMessage.val(NewMessageValue);
		textareaMessage.css('font-style', 'normal');
		textareaMessage.css('color', '#000');
		textareaMessage.unbind('click');
		textareaMessage.unbind('focus');
		textareaMessage.change(function(e){
			$('#ecard_text_size').text('characters: ' + textareaMessage.val().length);
			});
			
		textareaMessage.blur(function(e){
			$('#ecard_text_size').text('characters: ' + textareaMessage.val().length);
			});

		textareaMessage.keyup(function(e){
			$('#ecard_text_size').text('characters: ' + textareaMessage.val().length);
			});
			
		textareaMessage.mousemove(function(e){
			$('#ecard_text_size').text('characters: ' + textareaMessage.val().length);
			});
	}
	
	function ShowMessage()
	{
		$.post('a_ecard_message_form.aspx', function(eCardForm) {
			// format and output result
			if(eCardForm)
			{
				$('#eCard_work_box').remove();
				
				$('#eCardSpace').append(eCardForm);
				
				var parent_top = $('div.bottom_background').position_wSafariAuto().top + 200;
				var parent_left = $('div.bottom_background').position_wSafariAuto().left + 640;
				$('#eCard_work_box').css('top', parent_top + 'px');
				$('#eCard_work_box').css('left', parent_left + 'px');
				
				var CookieMessage = $.cookie('eCard_message');
				
				if ((CookieMessage != null) && (CookieMessage.length > 0))
				{
					eCardMessageBoxActivate(CookieMessage);
				}
				else
				{
					$('#ecard_text').click(function(e) {eCardMessageBoxActivate('');});
					$('#ecard_text').focus(function(e) {eCardMessageBoxActivate('');});
				}
				
				$('#backnext').show();
				$('#backnext a').unbind('click');
				$('#buttonBack').click(function(e){
					e.preventDefault();
					if(($('#ecard_text').val() == 'Enter your message here. Please note there is a 325 character limit.') || ($('#ecard_text').val().length == 0)){}
					else if ($('#ecard_text').val().length > 325) {}
					else
					{
						$.cookie('eCard_message', $('#ecard_text').val());
					}
					ShowFonts();
				});
				$('#buttonNext').click(function(e){
					e.preventDefault();
					if(($('#ecard_text').val() == 'Enter your message here. Please note there is a 325 character limit.') || ($('#ecard_text').val().length == 0))
					{
						$('#ecard_text_size').html('Please enter a message for your<br />eCard before continuing.');
					}
					else if ($('#ecard_text').val().length > 325)
					{
						$('#ecard_text_size').html('Your message exceeds the maximum<br /> allowed length of 325 characters.');
					}
					else
					{
						$.cookie('eCard_message', $('#ecard_text').val());
						ShowUserPreview();
					}
				});
			}
		});
	}
	
	function ShowPreviews()
	{
		WipeCardCookies();
		$.post('a_get_ecard_previews.aspx', function(eCardPreviews) {
			// format and output result
			if(eCardPreviews)
			{
				$('#eCard_work_box').remove();
				var myDiv = $('#eCardSpace').get(0);				
				// clear previous links from DOM
				var newDiv = myDiv.cloneNode(false);
				myDiv.parentNode.insertBefore(newDiv,myDiv);
				myDiv.parentNode.removeChild(myDiv);
				
				//create new page elements
				$('#eCardSpace').html(eCardPreviews);
				$('#backnext').hide();
				$('#backnext a').unbind('click');
				$('a.eCardPreview').click(function(e){
					e.preventDefault();
					CardPreview_Click($(this).attr('id'));
				});
			}
		});
	}
	
	function CaptchaComplete()
	{
		if($('#cap_frame').contents().find('#cap_success').get(0))
		{
			$('#cap_frame').unbind('load');
			$('#cap_frame').attr('src', '');
			$('#captcha_form_underlay').remove();
			var ChosenCardId = $.cookie('eCard_id');
			$.post('a_get_ecard_location.aspx', {CardID: ChosenCardId}, function(eCardLocation) {
				// format and output result
				if(eCardLocation)
				{
					var myDiv = $('#eCardSpace').get(0);				
					// clear previous links from DOM
					var newDiv = myDiv.cloneNode(false);
					myDiv.parentNode.insertBefore(newDiv,myDiv);
					myDiv.parentNode.removeChild(myDiv);
					
					//create new page elements
					$('#eCardSpace').html(eCardLocation + '<p id="backnext"><a id="buttonBack" href="">Back</a> | <a id="buttonNext" href="">Next</a></p>');
					ShowFonts();
				}
				else
				{
					$.cookie('eCard_id', null);
					$('#captcha_form_underlay').show();
				}
			});
		}
		else
		{
			$('#captcha_form_underlay').show();
		}
	}
	
	function CardPreview_Click(ChosenCardId)
	{
		$.cookie('eCard_id', ChosenCardId);
		
		var myDiv = $('#eCardSpace').get(0);				
		// clear previous links from DOM
		var newDiv = myDiv.cloneNode(false);
		myDiv.parentNode.insertBefore(newDiv,myDiv);
		myDiv.parentNode.removeChild(myDiv);
		
		$('#eCardSpace').append('<div id="captcha_form_underlay"><div id="captcha_form"><iframe id="cap_frame" src="./a_capt.aspx" /></div></div>');
		var parent_top = $('div.bottom_background').position_wSafariAuto().top;
		var parent_left = $('div.bottom_background').position_wSafariAuto().left + 230;
		$('#captcha_form_underlay').css('top', parent_top + 'px');
		$('#captcha_form_underlay').css('left', parent_left + 'px');
		$('#captcha_form_underlay').hide();
		$('#cap_frame').load(function(e){
			CaptchaComplete();
		});

	}

	$('a.eCardPreview').click(function(e){
		e.preventDefault();
		CardPreview_Click($(this).attr('id'));
	});
	
 });