var baseURL = "/corporate/";

jQuery.fn.extend({
	scrollTo : function(speed, easing) {
		return this.each(function() {
		var targetOffset = $(this).offset().top;
		$('html,body').animate({scrollTop: targetOffset}, speed, easing);
		});
	}
});


function stageOnePreview()
{
	return false;
}


function uploadCSV()
{		
		$.fancybox({ 'overlayShow' : true,
					'overlayColor' : '#000',
					'overlayOpacity' : 0.7,
					'type' : 'iframe',
					'href' : $(this).attr("href"),
					'scrolling' : 'no',
					'titleShow' : false,
					'hideOnOverlayClick' : false,
					'width' : 720,
					'height' : 500
		});
		
		return false;
}



function moveCarousel(carouselDirection)
{
	//Move it left
	if (carouselDirection == -1)
	{
		if (carouselPosition > 0)
		{
		
			carouselPosition--;
			
			$("#" + carouselName + " #carousel_list").animate(
			{	
				left: '+=' + itemWidth
			}, 200, 'easeInOutQuad', function() {
				// Animation complete.
				
				$("#carousel_button_right").removeClass();
				
				if (carouselPosition === 0)
				{
					$("#carousel_button_left").addClass("carousel_button_inactive");
				}
				
				});
		}
		
	}
	
	//Move it right
	if (carouselDirection == 1)
	{
		if (carouselPosition < (carouselItems - 3))
		{
			carouselPosition++;
		
			$("#" + carouselName + " #carousel_list").animate(
			{	
				left: '-=' + itemWidth
			}, 200, 'easeInOutQuad', function() {
				// Animation complete.
				
				$("#carousel_button_left").removeClass();
				
				if (carouselPosition == (carouselItems - 3))
				{
					$("#carousel_button_right").addClass("carousel_button_inactive");
				}
		
				});
		
		}
		
	}
}


function buildCarousel(idName)
{

	carouselName = idName;
	//Set initial position
	carouselPosition = 0;
	
	$("#" + carouselName + " #carousel_button_left").unbind();
	$("#" + carouselName + " #carousel_button_right").unbind();

		
	//Count list items, get size and right margin (assumes all identical)
	carouselItems = $("#" + carouselName + " li").size();
	
	
	itemWidth = parseInt($("#" + carouselName + " li").width(),10) + parseInt($("#" + carouselName + " li").css("margin-right"),10);
	
	//Set the scroll buttons
	$("#carousel_button_left").addClass("carousel_button_inactive");
	
	if (carouselItems < 4)
	{
		$("#carousel_button_right").addClass("carousel_button_inactive");
	} else {
		$("#carousel_button_right").removeClass();
	}
	
	//activate buttons
	$("#" + carouselName + " #carousel_button_left").bind("click",function(){
		moveCarousel(-1);
		return false;
	});
	
	$("#" + carouselName + " #carousel_button_right").bind("click",function(){
		moveCarousel(1);
		return false;
	});

}

function nextPreviousCard(currentCard,cardDirection,stage)
{
	if (!stage)
	{
		stage = 0;
	}

	$(".popup_preview_box").fadeOut("fast");
	$("#fancybox-inner").html("").load(baseURL + "ajax_functions/get_next_previous_card/" + currentCard + "/" + cardDirection,function(){
		
		var flashvars = {
							entered_message: $("#default_entered_message").val(),
							logo_url: $("#uploaded_logo").val(),
							flash_var1: $("#default_flash_var1").val(),
							flash_var2: $("#default_flash_var2").val(),
							flash_var3: $("#default_flash_var3").val(),
							flash_var4: $("#default_flash_var4").val(),
							flash_var5: $("#default_flash_var5").val(),
							swf_location: $("#ecard_holder").attr("data-card-location")
		};		
		
		swfobject.embedSWF($("#ecard_holder").attr("rel"), "ecard_holder", "480", "360", "9.0.0","",flashvars);
		
		$("#preview_button_left").bind("click",function(){
			nextPreviousCard($("#preview_button_left").attr("rel"),-1,stage);
			return false;
		});
		
		$("#preview_button_right").bind("click",function(){
			nextPreviousCard($("#preview_button_left").attr("rel"),1,stage);
			return false;
		});
	
		if (stage == 1)
		{
			$("#submit_form_preview").bind("click",function(){
				
				$.fancybox.close();
				$("#picker_list #" + $(this).attr("rel")).click();
				return false;
			});
		}
	
	});
		
	return false;
}

function forgotPasswordBox()
{
	var linkTarget = $(this);
	$("body").append('<div id="temp_content" style="display: none;"><div id="temp_content_inner"></div></div>');
	
	$('#temp_content_inner').load($(this).attr("href"), function(link) {
			
			$.fancybox({
							'overlayShow' : true,
							'overlayColor' : '#000',
							'overlayOpacity' : 0.7,
							'content' : link,
							'scrolling' : 'no',
							'width' : "700px",
							'height' : "560px",
							'titleShow' : false,
							'showCloseButton' : true,
							'onComplete' : function(){
								
								$("#fancybox-wrap").css({"width" : "288px"});
								$("#temp_content").remove();
								
								$("#reset_password_form").bind("submit",resetPassword);
								
								Cufon.replace('#reset_password_box h2');
							}
					});
					
		});
	
	return false;
}


function resetPassword()
{	
	var link = "/corporate/ajax_functions/reset_password/" + $("#reset_email_address").val();
		
	$('#fancybox-inner').load(link,function(link){
		$("#reset_password_form").bind("submit",resetPassword);
		Cufon.replace('#reset_password_box h2');
	});
	
	return false;
}

function showLoginBox()
{
	//Load the preview HTML via jquery into a temporary div which is later removed by Fancybox. 
		//Doing the AJAX directly through Fancybox seems to confuse IE in to thinking it's looking at a separate domain and breaks the AJAX.
		//Anybody who thinks they can fix this - be my guest!
		
		var link = "/corporate/ajax_functions/get_login_box";
		$("body").append('<div id="temp_content" style="display: none;"><div id="temp_content_inner"></div></div>');
		$('#temp_content_inner').load(link, function(link) {
			
			$.fancybox({
					'overlayShow' : true,
					'overlayColor' : '#000',
					'overlayOpacity' : 0.7,
					'content' : link,
					'scrolling' : 'no',
					'width' : "700px",
					'height' : "560px",
					'titleShow' : false,
					'showCloseButton' : true,
					'onComplete' : function(){
						
						$("#fancybox-wrap").css({"width" : "288px"});
						$("#temp_content").remove();
						
						Cufon.replace('#log_in_box h2');
						$("#forgotten_password_link").bind("click",forgotPasswordBox);
						addPlaceholders();
					}
			});
					
		});
		
		
	return false;
}


function bindFancyboxPreview(stage)
{
	if (!stage)
	{
		stage = 0;
	}

	$("a.card_preview_link").bind("click",function(){
		
		//Load the preview HTML via jquery into a temporary div which is later removed by Fancybox. 
		//Doing the AJAX directly through Fancybox seems to confuse IE in to thinking it's looking at a separate domain and breaks the AJAX.
		//Anybody who thinks they can fix this - be my guest!
		
		var link = $(this).attr('href');
		$("body").append('<div id="temp_content" style="display: none;"><div id="temp_content_inner"></div></div>');
		$('#temp_content_inner').load(link, function(link) 
		
		{
		
			$.fancybox({
					'overlayShow' : true,
					'overlayColor' : '#000',
					'overlayOpacity' : 0.7,
					'content' : link,
					'scrolling' : 'no',
					'width' : "700px",
					'height' : "560px",
					'titleShow' : false,
					'showCloseButton' : true,
					'onComplete' : function(){
						
						$("#fancybox-wrap").css({"height" : "490px", "width" : "600px"});
						
						$("#temp_content").remove();
						
						var flashvars = {};
						
						if (stage >= 2)
						{
							flashvars = {
								entered_message: encodeURIComponent($("#message").val()),
								logo_url: encodeURIComponent($("#uploaded_logo").val()),
								flash_var1: encodeURIComponent($("#flash_var1").val()),
								flash_var2: encodeURIComponent($("#flash_var2").val()),
								flash_var3: encodeURIComponent($("#flash_var3").val()),
								flash_var4: encodeURIComponent($("#flash_var4").val()),
								flash_var5: encodeURIComponent($("#flash_var5").val()),
								swf_location: $("#ecard_holder").attr("data-card-location")
						
							};					
							
						} 
						else
						{
							flashvars = {
								entered_message: encodeURIComponent($("#default_entered_message").val()),
								logo_url: encodeURIComponent($("#uploaded_logo").val()),
								flash_var1: encodeURIComponent($("#default_flash_var1").val()),
								flash_var2: encodeURIComponent($("#default_flash_var2").val()),
								flash_var3: encodeURIComponent($("#default_flash_var3").val()),
								flash_var4: encodeURIComponent($("#default_flash_var4").val()),
								flash_var5: encodeURIComponent($("#default_flash_var5").val()),
								swf_location: $("#ecard_holder").attr("data-card-location")
							};
													
						}
						
						swfobject.embedSWF($("#ecard_holder").attr("rel"), "ecard_holder", "480", "360", "9.0.0","",flashvars);
						
						$("#submit_form_preview").unbind("click");
						
						if (stage > 1)
						{
							$("#submit_form_preview").remove();
							$("#preview_button_left,#preview_button_right").remove();
						}
						
						
						if (stage != 2)
						{
						
							$("#preview_button_left").bind("click",function(){
							
								nextPreviousCard($("#preview_button_left").attr("rel"),-1,stage);
								return false;
							});
							
							$("#preview_button_right").bind("click",function(){
								nextPreviousCard($("#preview_button_left").attr("rel"),1,stage);
								return false;
							});
						}
						
						
						if (stage == 1)
						{
							$("#submit_form_preview").bind("click",function(){
								$.fancybox.close();
							$("#picker_list #" + $(this).attr("rel")).click();
							return false;
						});
						}
						
					}
			});
		
		});
		
			
				
		
		return false;
		
	});

}


function clickTab(tabName,tabData)
{
	$("#" + tabBarName + " li").removeClass();
	$("#" + tabName).addClass("active_tab");
	
	//Fade out list
	$("#" + contentToChange).animate(
			{	
			
				opacity: 0
			}, 200, 'easeInOutQuad', function() {
				// Get the new content.
				
				
				$("#" + contentToChange).load(baseURL + "ajax_functions/get_carousel_data/" + tabName, function() {
				
					$("#" + contentToChange).css("left",buttonWidth);
											
					//Fade back in
					$("#" + contentToChange).animate(
						{	
							opacity: 1
						}, 200, 'easeInOutQuad', function() {
						// Animation complete.
						buildCarousel("home_carousel");
						$(".card_preview_link").unbind();
						bindFancyboxPreview();
						});
					});
				});	
}


//Takes two variables - the id of the tab bar list, and the id of the list who's content is to be changed. Name attribute of the links in the tabs should be the same as the category names in the database
function buildTabBox(tabBarId,tabbedContent)
{

	tabBarName = tabBarId;
	contentToChange = tabbedContent;
	
	//Set initially selected tab
	tabBarSelected = "tab0";
	
	//activate tabs
	$("#" + tabBarName + " li").bind("click",function(){
		
		clickTab($(this).attr("id"),$("a",this).attr("name"));
		return false;
	});
	
	
}



function reloadPreviewBox(newCard)
{

	//Fade out list
	$("#preview_data").animate(
	{	
		opacity: 0
	}, 200, 'easeInOutQuad', function() {
		// Get the new content.
		
	$("#preview_data").load(baseURL + "ajax_functions/get_preview_box/" + newCard, function() {
									
		//Fade back in
		$("#preview_data").animate(
			{	
				opacity: 1
			}, 200, 'easeInOutQuad', function() {
			// Animation complete.
			$(".card_preview_link").unbind();
			bindFancyboxPreview(1);
			});
		});
	});
	
}



function bindPickerButtons()
{

	$("#picker_list input").bind("click",function(){
				
		$("#picker_list li").attr("id","");
		$(this).parents("li").attr("id","selected_card_image");
		reloadPreviewBox($(this).val());
		
	});

}



function clickTabPicker(tabName,tabData)
{

	$("#" + tabBarName + " li").removeClass();
	$("#" + tabName).addClass("active_tab");
	
	//Fade out list
	$("#" + contentToChange).animate(
	{	
	
		opacity: 0
	}, 200, 'easeInOutQuad', function() {
		// Get the new content.
		
		
		$("#" + contentToChange).load(baseURL + "ajax_functions/get_picker_data/" + tabName, function() {
													
			//Fade back in
			$("#" + contentToChange).animate(
				{	
					opacity: 1
				}, 200, 'easeInOutQuad', function() {
				// Animation complete.
				$(".card_preview_link").unbind();
					bindPickerButtons();
					$("#picker_list input[checked=checked]").click();
					bindFancyboxPreview();
				});
			});
		});	
	
}




//Takes two variables - the id of the tab bar list, and the id of the list who's content is to be changed. Name attribute of the links in the tabs should be the same as the category names in the database
function buildCardPicker(tabBarId,tabbedContent)
{
	tabBarName = tabBarId;
	contentToChange = tabbedContent;
	
	//Set initially selected tab
	tabBarSelected = "all";
	
	//activate tabs
	$("#" + tabBarName + " li").bind("click",function(){
		clickTabPicker($(this).attr("id"),$("a",this).attr("name"));
		return false;
	});
	
	
}






function bindPopupDescriptions()
{
	$("body").append("<div id=\"popup_description_display\"></div>");

	$(".card_thumbnail_item").live("mouseover",function()
	{
		$("#popup_description_display").html($(".popup_description",this).html()).show();
		$(document).bind("mousemove",function(e){
			$("#popup_description_display").css({
            top: (e.pageY + 15) + "px",
            left: (e.pageX + 15) + "px"
        });
		});
	
	});
	
	$(".card_thumbnail_item").live("mouseout",function()
	{
		$("#popup_description_display").hide();
		$(document).unbind("mousemove");
	});
}


function clearPlaceholder()
{
	if (($(this).val() === "") || ($(this).val() == $(this).attr("placeholder")))
	{
		$(this).val("").css("color",$(this).attr("data-oldtext"));
	}
}

function replacePlaceholder()
{	
	if (($(this).val() === "") || ($(this).val() == $(this).attr("placeholder")))
	{
		$(this).val($(this).attr("placeholder")).css("color","#999");
	}
}

function checkPasswordPlaceholder()
{
	if ($(this).val() === "")
	{
		$(this).hide();
		$("#dummy_" + $(this).attr("id")).show();
	}	
}


function supportsInputPlaceholder() 
{
	var i = document.createElement('input');
	return 'placeholder' in i;
}



function addPlaceholders()
{

	//Placeholder support
	if (!supportsInputPlaceholder())
	{
		$("input,textarea").each(function(){
		
			if ((($(this).attr("placeholder")) && ($(this).val() === "")) || ($(this).attr("placeholder") == $(this).val()))
			{
			
				$(this).attr("data-oldtext",$(this).css("color")).val($(this).attr("placeholder")).css("color","#999").bind("focus",clearPlaceholder).bind("blur",replacePlaceholder);
				
				//Handle Password type - create a dummy text field to switch with the password field, as you can't change type in jquery
				if ($(this).attr("type") == "password")
				{
					$(this).before("<input value=\"" + $(this).attr("placeholder") + "\" readonly=\"readonly\" type=\"text\" style=\"color: #999\" class=\"" + $(this).attr("class") + "\" id=\"dummy_" + $(this).attr("id") + "\"/>").hide().unbind("blur").unbind("focus").bind("blur",checkPasswordPlaceholder).val("").css("color",$(this).attr("data-oldtext"));
					
					$("#dummy_" + $(this).attr("id")).bind("focus",function(){
						$(this).hide().next().show().focus();
					});
				}
			}
		
		});
	}
}


function bindUploadImage(uploadButton)
{
	$(uploadButton).bind("click",function(){
		var uploadLink = $(this).attr("rel");
		
		$.fancybox({ 'overlayShow' : true,
					'overlayColor' : '#000',
					'overlayOpacity' : 0.7,
					'type' : 'iframe',
					'href' : uploadLink,
					'scrolling' : 'no',
					'titleShow' : false,
					'hideOnOverlayClick' : false,
					'width' : 720,
					'height' : 500
		});
		
		return false;
	});

}

function initImageUpload()
{	
												
	
}

function initCSVUpload()
{

}


function jsUpload(upload_field)
{
    // this is just an example of checking file extensions
    // if you do not need extension checking, remove 
    // everything down to line
    // upload_field.form.submit();

    var re_text = /\.jpg|\.png|\.jpeg|\.gif/i;
    var filename = upload_field.value;

    /* Checking file type */
    if (filename.search(re_text) == -1)
    {
        //alert("File is not a valid image (.jpg, .png or .gif)");
       // upload_field.form.reset();
        //return false;
    }

    upload_field.form.submit();
    upload_field.disabled = true;
    return true;

}




var inlineFormValidate = {
	// standard regexp
	textBoxRegExp: "^.{1,300}$",
	passwordRegExp: "^.{6,256}$",
	textAreaRegExp: "^.{1,3000}$",
	emailRegExp: "^([\\da-zA-Z-_+][\\da-zA-Z-_+.\\w']*[\\da-zA-Z-_+]@[\\da-zA-Z]['-.\\w]*[\\da-zA-Z]\\.[a-zA-Z]{2,7})$",
	postcodeRegExp:"^([A-Z0-9][A-Z0-9][A-Z0-9]?[A-Z0-9]? {0,2}[0-9][A-Z]{2}|GIR 0AA)$",
	phoneRegExp:"^0[1237][\\d ]{5,18}$",
	dateOfBirthRegExp:"^\\d{2,}\/[01]\\d\/19\\d{2,}$",
	amountRegExp:"^\\d{1,10}\\.?\\d{0,2}$",
	secCodeRegExp:"^[0-9]{3}$",
	issueRegExp:"^[0-9]{1,2}$",
	urlRegExp:"^" + baseURL + "uploadimages/images/[0-9]{9,12}_upload.jpg$",
	
	warningBox_0: '<div id="',
	warningBox_1: '" class="warning_holder" style="display:none;"><div class="warning_pointer"></div><div class="warning_text"><div class="warning_exclamation"></div><span class="warning_text_area">',
	warningBox_2: '</span></div></div>',
	
	hideWarningBox: function(rowID) {
		$("#" + rowID).fadeOut(function() {
			$(this).remove();
		});
	},
		
	showWarningBox: function(warningID,message,originator,xOffset){

		
		if ($("#" + warningID).length > 0)
		{
			$("#" + warningID + " .warning_text_area").html(message);
		} else {
			var bodyPos = $("#body_content").offset();
			var originatorPos = $("#" + originator).offset();
			
			$("#body_content").append(inlineFormValidate.warningBox_0 + warningID + inlineFormValidate.warningBox_1 + message + inlineFormValidate.warningBox_2);
			
			$("#" + warningID).css('left',xOffset);
			
			$("#" + warningID).css('top',(originatorPos.top - bodyPos.top  - 8));

			$("#" + warningID).fadeIn();
		}
	},	
		
	checkField: function (field, regExCheck, required) {
		var regExLine = new RegExp(regExCheck, "i");
		var fieldID = "#" + field;
		var fieldVal = jQuery.trim($(fieldID).val());
		var placeholderVal = jQuery.trim($(fieldID).attr("placeholder"));
		
		if (placeholderVal && (fieldVal == placeholderVal)) {
				fieldVal = "";
		}
				
		
		//Check if the field has been accessed before
		if ($(fieldID).hasClass('tested')) {
		
			if (regExLine.test(fieldVal)) {
						
				if (fieldVal !== "" || (fieldVal === "" && required == 1)) {
					return 0;
				} else {
					return 2;
				}
			} else {
				if (fieldVal === "" && required === 0) {
					return 0;
				} else {
					return 1;
				}
			}
		} else {
			return 0;
		}

	}, // checkField
	
	
	checkDropDown: function (field, emptyValue, required) {
		var fieldID = "#" + field;
		var fieldVal = $(fieldID + " option:selected").val();
		

		if ($(fieldID).hasClass('tested')) {
				
			if ((fieldVal == emptyValue) && (required !== 0)) {
				return 1;
								
			} else {
					
				return 0;
			}
		
		} else {
			return 0;
		}
	}, // end checkDropDown
	
	
	/**
	* Basic credit card number check using Luhn algorithm 
	* Strips out the white space and letters
	* Does not do a check for proper issuers prefix
	**/
	checkCardNumberField: function (field, required) {
		var fieldID = "#" + field;
		var fieldVal = jQuery.trim($(fieldID).val());

		// Strip any non-digits (useful for credit card numbers with spaces and hyphens)
		fieldVal = fieldVal.replace(/\D/g, '');

		if (fieldVal.length <= 19) {
			// Set the string length and parity
			var number_length = fieldVal.length;
			var parity = number_length % 2;

			// Loop through each digit and do the maths
			var total=0;
			for (i=0; i < number_length; i++) {
				var digit = fieldVal.charAt(i);
				// Multiply alternate digits by two
				if (i % 2 == parity) {
					digit=digit * 2;
					// If the sum is two digits, add them together (in effect)
					if (digit > 9) {
						digit=digit - 9;
					}
				}
				// Total up the digits
				total = total + parseInt(digit, 10);
			}
		}

		// If the total mod 10 equals 0, the number is valid
		if (total % 10 === 0 && fieldVal.length >= 12 && fieldVal.length <= 19) {
			if (fieldVal !== "" || (fieldVal === "" && required === 0)) {
				return 0;
			} else {
				return 0;
			}
			
		} else {
			if (fieldVal !== "" || (fieldVal === "" && required == 1)) {
					return 1;
			}
		}

		// replace value with whitespace trimmed version
		$(fieldID).val(fieldVal);
	} // end checkCardNumberField
	
	
};
// end inlineFomValidate object


function testEmailRecipient(i,source)
{


	if (source == "email")
	{
		$("#email_" + i).addClass("tested");
	}
	
	if (source == "name")
	{
		$("#to_name_" + i).addClass("tested");
	}

	if($("#email_" + i).hasClass("tested") && $("#to_name_" + i).hasClass("tested")) {


		if (jQuery.trim($("#to_name_" + i).val()) || jQuery.trim($("#email_" + i).val()))
			{
				
				//Test there's something in the fields
				var recipNameCheck = inlineFormValidate.checkField("to_name_" + i, inlineFormValidate.textBoxRegExp, 1);
				var recipEmailCheck = inlineFormValidate.checkField("email_" + i, inlineFormValidate.emailRegExp, 1);
								
				if ((recipNameCheck !== 0) && (recipEmailCheck === 0))
				{			
					inlineFormValidate.showWarningBox("row_" + i,"Please enter a name","to_name_" + i,670);
					$("#email_" + i).addClass('validated').removeClass('has_error');
					$("#to_name_" + i).addClass('has_error').removeClass('validated');
					return 0;
				}
				
				if ((recipNameCheck === 0) && (recipEmailCheck !== 0))
				{
								
					inlineFormValidate.showWarningBox("row_" + i,"Please enter a valid email","email_" + i,670);
					$("#email_" + i).addClass('has_error').removeClass('validated');
					$("#to_name_" + i).addClass('validated').removeClass('has_error');
					return 0;
				}
				
				if ((recipNameCheck !== 0) && (recipEmailCheck !== 0))
				{			
					inlineFormValidate.showWarningBox("row_" + i,"Please enter a name and valid email","email_" + i,670);
					$("#email_" + i).addClass('has_error').removeClass('validated');
					$("#to_name_" + i).addClass('has_error').removeClass('validated');
					return 0;
				}
				
				if ((recipNameCheck === 0) && (recipEmailCheck === 0))
				{	
					inlineFormValidate.hideWarningBox("row_" + i);		
					$("#email_" + i).removeClass('has_error').addClass('validated');
					$("#to_name_" + i).removeClass('has_error').addClass('validated');
					
					return 1;
				}
				
			} else {
							
				$("#to_name_" + i).removeClass('validated has_error');
				$("#email_" + i).removeClass('validated has_error');
				inlineFormValidate.hideWarningBox("row_" + i);
				
				return 2;
			}
	}
	
}



function addMoreRecipients() {
		extraRecipient = '<li class="clearfix" id="recipientXX" style="display: none;"><div class="row_number">XX.</div><div class="recipient_name_col"><span class="input_wrap"><input class="form_text_field placeholder_field" type="text" id="to_name_YY" name="to_name_YY" placeholder="Recipient&rsquo;s name" data-index="YY" /></span></div><div class="recipient_email_col"><span class="input_wrap"><input class="form_text_field placeholder_field" type="text" id="email_YY" name="email_YY" placeholder="their email address" data-index="YY" /></span></div></li>';
	
		if (emailRecipients < 121)
		{
			var startNumber = emailRecipients + 1;
			emailRecipients = emailRecipients + 5;
			
			for (i=5;i>0;i--)
			{
				var newLine = extraRecipient.replace( new RegExp( "XX", "g" ), startNumber );
				newLine = newLine.replace( new RegExp( "YY", "g" ), (startNumber-1) );
				
				$("#recipient_list").append(newLine);
				$("#recipient" + startNumber).fadeIn();
				
				//On blur...
				$("#to_name_" + (startNumber-1)).bind("blur",function() {
					testEmailRecipient($(this).attr("data-index"),"name");
				});
				
				$("#email_" + (startNumber-1)).bind("blur",function() {
					testEmailRecipient($(this).attr("data-index"),"email");
				});
				
				startNumber++;
				
				if (startNumber > 120)
				{
					$("#add_more_recipients").fadeOut(function(){
						$(this).remove();
					});
				}
			}
			
			
			$("#add_more_recipients").scrollTo();		
			addPlaceholders();
		}
		else
		{
			$("#add_more_recipients").fadeOut(function(){
				$(this).remove();
			});
		}
				
		return false;
}


function checkHeadlines(warningOffset,triggeringField)
{
	$("#" + triggeringField).addClass("tested");
	var h1Check = inlineFormValidate.checkField("flash_var1", inlineFormValidate.textBoxRegExp, 1);
	var h2Check = inlineFormValidate.checkField("flash_var2", inlineFormValidate.textBoxRegExp, 1);
	var h3Check = inlineFormValidate.checkField("flash_var3", inlineFormValidate.emailRegExp, 1);
	

	
	if ((h1Check === 1) && (h2Check === 1) && (h3Check === 1)) {
		inlineFormValidate.showWarningBox("hl_1","Please enter at least one headline","flash_var1",warningOffset);
		$("#flash_var1,#flash_var2,#flash_var3").addClass('has_error').removeClass('validated');
	} 
	else
	{
		inlineFormValidate.hideWarningBox("hl_1");
		$("#flash_var1,#flash_var2,#flash_var3").removeClass('has_error');
	}
	
	
	if ($("#" + triggeringField).val() !== "")
	{
		$("#" + triggeringField).addClass('validated');
	}
}




function checkEmailRecipients() 
{
	$("input").addClass("tested");

	//Remove placeholders for IE
	$("input").each(function(){
		if ($(this).val() == $(this).attr("placeholder"))
		{
			$(this).val("");
		}
	});
	
	var recipientCount = $("#recipient_list li").length;

	validRecipients = 0;
	errorRecipients = 0;

	for (i=0;i<recipientCount;i++)
	{	
		var testReturn = testEmailRecipient(i,"all");
		
		if (testReturn === 0)
		{
			errorRecipients++;
		}
		
		if (testReturn == 1)
		{
			validRecipients++;
		}
		
	}
	
	if (validRecipients>0)
	{
		return 1;
	} else {
		
		if (errorRecipients === 0)
		{
			inlineFormValidate.showWarningBox("row_1","Please enter at least one recipient","to_name_0",670);
			$("#email_0").addClass('has_error').removeClass('validated');
			$("#to_name_0").addClass('has_error').removeClass('validated');
		}
		return 0;
	}	
}



//Field checks

function cardAmountSelected(warningOffset) 
{
	
	if (!$("input[name=card_amount]:checked").val())
	{
		inlineFormValidate.showWarningBox("row_0","Please select how many cards you wish to send","more_1500",warningOffset);
		$("#more_1500").addClass('has_error');
		
	} else {
		inlineFormValidate.hideWarningBox("row_0");
		$("#more_1500").removeClass('has_error');
	}
}

function checkPassword(warningOffset) 
{
	var triggeringVariable = "#password";
	$("#password").addClass("tested");
	
	var passwordCheck = inlineFormValidate.checkField("password", inlineFormValidate.passwordRegExp, 1);
	
	if (passwordCheck === 0) 
	{	
		if ($("#confirm_password").hasClass("tested"))
		{
			if ($("#confirm_password").val() !== $("#password").val())
			{
				inlineFormValidate.showWarningBox("row_4","Passwords do not match","password",warningOffset);
				$("#confirm_password, #password").removeClass('validated').addClass('has_error');
			} else {
				inlineFormValidate.hideWarningBox("row_4");
				$("#confirm_password, #password").addClass('validated').removeClass('has_error');
			}
		} else {
			inlineFormValidate.hideWarningBox("row_4");
			$(triggeringVariable).addClass('validated').removeClass('has_error');
		}
			
	} else {
		inlineFormValidate.showWarningBox("row_4","Your password must contain at least 6 characters","password",warningOffset);
		$(triggeringVariable).removeClass('validated').addClass('has_error');
		$("#confirm_password").removeClass('validated');
	}
	
	
}

function checkPasswordConfirm(warningOffset) {
	var triggeringVariable = "#confirm_password";
	$("#password, #confirm_password").addClass("tested");
	
	var passwordCheck = inlineFormValidate.checkField("password", inlineFormValidate.passwordRegExp, 1);
	
	if (passwordCheck === 0) 
	{
		if ($("#confirm_password").val() !== $("#password").val())
		{
			inlineFormValidate.showWarningBox("row_4","Passwords do not match","password",warningOffset);
			$("#confirm_password, #password").removeClass('validated').addClass('has_error');
		} else {
			inlineFormValidate.hideWarningBox("row_4");
			$("#confirm_password, #password").addClass('validated').removeClass('has_error');
		}
	} else {
		$("#confirm_password").removeClass('validated');
	}
}


function checkTitleSender(warningOffset) {
	var triggeringVariable = "#title";
	$("#title").addClass("tested");
		
		var firstNameCheck = inlineFormValidate.checkField("first_name", inlineFormValidate.textBoxRegExp, 1);
		var lastNameCheck = inlineFormValidate.checkField("last_name", inlineFormValidate.textBoxRegExp, 1);
		var titleCheck = inlineFormValidate.checkDropDown("title", "", 1);
		
				
		if ((firstNameCheck === 0) && (lastNameCheck === 0) && (titleCheck === 0)) {
			inlineFormValidate.hideWarningBox("row_1");
			$(triggeringVariable).addClass('validated').removeClass('has_error');
			
		} else {
		
			if ((firstNameCheck === 0) && (lastNameCheck === 0) && (titleCheck == 1)) {
				$(triggeringVariable).addClass('validated');
				inlineFormValidate.showWarningBox("row_1","Please enter your title","first_name",warningOffset);	
			} else if ((firstNameCheck === 0) && (lastNameCheck == 1) && (titleCheck === 0)) {
				inlineFormValidate.showWarningBox("row_1","Please enter your last name","first_name",warningOffset);
				$(triggeringVariable).addClass('validated');
			} else if ((firstNameCheck == 1) && (lastNameCheck === 0) && (titleCheck === 0)) {
				inlineFormValidate.showWarningBox("row_1","Please enter your first name","first_name",warningOffset);
				$(triggeringVariable).removeClass('validated');
			} else if ((firstNameCheck === 0) && (lastNameCheck == 1) && (titleCheck == 1)) {
				inlineFormValidate.showWarningBox("row_1","Please enter your last name and title","first_name",warningOffset);
				$(triggeringVariable).addClass('validated');
			} else if ((firstNameCheck == 1) && (lastNameCheck == 1) && (titleCheck === 0)) {
				inlineFormValidate.showWarningBox("row_1","Please enter your first name and last name","first_name",warningOffset);
				$(triggeringVariable).removeClass('validated');
			} else if ((firstNameCheck == 1) && (lastNameCheck === 0) && (titleCheck == 1)) {
				inlineFormValidate.showWarningBox("row_1","Please enter your first name and title","first_name",warningOffset);
				$(triggeringVariable).removeClass('validated');
			} else if ((firstNameCheck == 1) && (lastNameCheck == 1) && (titleCheck == 1)) {
				inlineFormValidate.showWarningBox("row_1","Please enter your first name, last name and title","first_name",warningOffset);
				$(triggeringVariable).removeClass('validated');
			}
		}
}


function checkSenderName(warningOffset) {
	var triggeringVariable = "#personalisation_from_name";
	$(triggeringVariable).addClass("tested");
	
	var nameCheck = inlineFormValidate.checkField("personalisation_from_name", inlineFormValidate.textBoxRegExp, 1);
	
	if (nameCheck == 1) 
	{
		$(triggeringVariable).addClass('has_error').removeClass('validated');
		inlineFormValidate.showWarningBox("row_1","Please enter the name you would like your cards to come from","personalisation_from_name",warningOffset);
	} else {
		inlineFormValidate.hideWarningBox("row_1");
		$(triggeringVariable).addClass('validated').removeClass('has_error');
	}
}


function checkFirstNameSender(warningOffset) {
	var triggeringVariable = "#first_name";
	$("#title").change();
	$(triggeringVariable).addClass("tested");
		
		var firstNameCheck = inlineFormValidate.checkField("first_name", inlineFormValidate.textBoxRegExp, 1);
		var lastNameCheck = inlineFormValidate.checkField("last_name", inlineFormValidate.textBoxRegExp, 1);
		var titleCheck = inlineFormValidate.checkDropDown("title", "", 1);
		
		//alert(firstNameCheck + lastNameCheck + emailCheck);
				
		if ((firstNameCheck === 0) && (lastNameCheck === 0) && (titleCheck === 0)) {
			inlineFormValidate.hideWarningBox("row_1");
			$(triggeringVariable).addClass('validated').removeClass('has_error');
			
		} else {
		
			if ((firstNameCheck === 0) && (lastNameCheck === 0) && (titleCheck == 1)) {
				$(triggeringVariable).addClass('validated').removeClass('has_error');
				inlineFormValidate.showWarningBox("row_1","Please enter your title","first_name",warningOffset);	
			} else if ((firstNameCheck === 0) && (lastNameCheck == 1) && (titleCheck === 0)) {
				inlineFormValidate.showWarningBox("row_1","Please enter your last name","first_name",warningOffset);
				$(triggeringVariable).addClass('validated').removeClass('has_error');
			} else if ((firstNameCheck == 1) && (lastNameCheck === 0) && (titleCheck === 0)) {
				inlineFormValidate.showWarningBox("row_1","Please enter your first name","first_name",warningOffset);
				$(triggeringVariable).addClass('has_error').removeClass('validated');
			} else if ((firstNameCheck === 0) && (lastNameCheck == 1) && (titleCheck == 1)) {
				inlineFormValidate.showWarningBox("row_1","Please enter your last name and title","first_name",warningOffset);
				$(triggeringVariable).addClass('validated').removeClass('has_error');
			} else if ((firstNameCheck == 1) && (lastNameCheck == 1) && (titleCheck === 0)) {
				inlineFormValidate.showWarningBox("row_1","Please enter your first name and last name","first_name",warningOffset);
				$(triggeringVariable).addClass('has_error').removeClass('validated');
			} else if ((firstNameCheck == 1) && (lastNameCheck === 0) && (titleCheck == 1)) {
				inlineFormValidate.showWarningBox("row_1","Please enter your first name and title","first_name",warningOffset);
				$(triggeringVariable).addClass('has_error').removeClass('validated');
			} else if ((firstNameCheck == 1) && (lastNameCheck == 1) && (titleCheck == 1)) {
				inlineFormValidate.showWarningBox("row_1","Please enter your first name, last name and title","first_name",warningOffset);
				$(triggeringVariable).addClass('has_error').removeClass('validated');
			}
		}
		
		
		
}

function checkLastNameSender(warningOffset) {
	var triggeringVariable = "#last_name";
	$("#title").change();
	$(triggeringVariable).addClass("tested");
		
		var firstNameCheck = inlineFormValidate.checkField("first_name", inlineFormValidate.textBoxRegExp, 1);
		var lastNameCheck = inlineFormValidate.checkField("last_name", inlineFormValidate.textBoxRegExp, 1);
		var titleCheck = inlineFormValidate.checkDropDown("title", "", 1);
				
		//alert(firstNameCheck + lastNameCheck + emailCheck);
				
		if ((firstNameCheck === 0) && (lastNameCheck === 0) && (titleCheck === 0)) {
			inlineFormValidate.hideWarningBox("row_1");
			$(triggeringVariable).addClass('validated').removeClass('has_error');
			
		} else {
		
			if ((firstNameCheck === 0) && (lastNameCheck === 0) && (titleCheck == 1)) {
				$(triggeringVariable).addClass('validated').removeClass('has_error');
				inlineFormValidate.showWarningBox("row_1","Please enter your title","first_name",warningOffset);	
			} else if ((firstNameCheck === 0) && (lastNameCheck == 1) && (titleCheck === 0)) {
				inlineFormValidate.showWarningBox("row_1","Please enter your last name","first_name",warningOffset);
				$(triggeringVariable).addClass('has_error').removeClass('validated');
			} else if ((firstNameCheck == 1) && (lastNameCheck === 0) && (titleCheck === 0)) {
				inlineFormValidate.showWarningBox("row_1","Please enter your first name","first_name",warningOffset);
				$(triggeringVariable).addClass('validated').removeClass('has_error');
			} else if ((firstNameCheck === 0) && (lastNameCheck == 1) && (titleCheck == 1)) {
				inlineFormValidate.showWarningBox("row_1","Please enter your last name and title","first_name",warningOffset);
				$(triggeringVariable).addClass('has_error').removeClass('validated');
			} else if ((firstNameCheck == 1) && (lastNameCheck == 1) && (titleCheck === 0)) {
				inlineFormValidate.showWarningBox("row_1","Please enter your first name and last name","first_name",warningOffset);
				$(triggeringVariable).addClass('has_error').removeClass('validated');
			} else if ((firstNameCheck == 1) && (lastNameCheck === 0) && (titleCheck == 1)) {
				inlineFormValidate.showWarningBox("row_1","Please enter your first name and title","first_name",warningOffset);
				$(triggeringVariable).addClass('validated').removeClass('has_error');
			} else if ((firstNameCheck == 1) && (lastNameCheck == 1) && (titleCheck == 1)) {
				inlineFormValidate.showWarningBox("row_1","Please enter your first name, last name and title","first_name",warningOffset);
				$(triggeringVariable).addClass('has_error').removeClass('validated');
			}
		}
}

function checkLogoUploaded(warningOffset)
{
	var triggeringVariable = "#uploaded_logo";
	$(triggeringVariable).addClass("tested");
	
	var imageUploadCheck = inlineFormValidate.checkField("uploaded_logo", inlineFormValidate.textBoxRegExp, 1);
	
	if (imageUploadCheck === 0) {
			inlineFormValidate.hideWarningBox("row_image");
			$(triggeringVariable).addClass('validated').removeClass('has_error');
			
	} else {
		
			inlineFormValidate.showWarningBox("row_image","Please upload an image","choose_image_button",warningOffset);
			$(triggeringVariable).addClass('has_error').removeClass('validated');
	}
}

function checkEmailSender(warningOffset) 
{
	var triggeringVariable = "#email_address";
	$(triggeringVariable).addClass("tested");
		
		
		var emailCheck = inlineFormValidate.checkField("email_address", inlineFormValidate.emailRegExp, 1);
		
			
		if (emailCheck === 0) {
		
			//Check if user already registered...
			
			$.ajax({
  				url: baseURL + 'ajax_functions/check_email_address/' + $("#email_address").val(),
  				success: function(data) {
    				
    				//Already registered
    				if (data == 1)
    				{
    					$(triggeringVariable).addClass('has_error').removeClass('validated');
						inlineFormValidate.showWarningBox("row_3","An account has already been set up using this account. You can log in using the box at the top of this page","email_address",warningOffset);
    				} else {
    					inlineFormValidate.hideWarningBox("row_3");
						$(triggeringVariable).addClass('validated').removeClass('has_error');
    				}
    				
  				},
  				error: function() {
  					$(triggeringVariable).addClass('has_error').removeClass('validated');
					inlineFormValidate.showWarningBox("row_3","Cannot connect to database","email_address",warningOffset);
  				}
			});
					
		} else {
			$(triggeringVariable).addClass('has_error').removeClass('validated');
			inlineFormValidate.showWarningBox("row_3","Please enter your email address","email_address",warningOffset);	
		} 
}


function checkCompanySender(warningOffset) 
{
	var triggeringVariable = "#company_name";
	$(triggeringVariable).addClass("tested");
		
		var companyCheck = inlineFormValidate.checkField("company_name", inlineFormValidate.textBoxRegExp, 1);
					
		if (companyCheck === 0) {
			inlineFormValidate.hideWarningBox("row_6");
			$(triggeringVariable).addClass('validated').removeClass('has_error');
			
		} else {
			$(triggeringVariable).addClass('has_error').removeClass('validated');
			inlineFormValidate.showWarningBox("row_6","Please enter your company&rsquo;s name","company_name",warningOffset);	
		} 
}



function checkNamePayment(warningOffset) {
	var triggeringVariable = "#name";
	$(triggeringVariable).addClass("tested");
		
		var nameCheck = inlineFormValidate.checkField("name", inlineFormValidate.textBoxRegExp, 1);
				
		if (nameCheck !== 0)
		{
			inlineFormValidate.showWarningBox("row_1","Please enter your name","name",warningOffset);
			$(triggeringVariable).addClass('has_error').removeClass('validated');
		} else {
			inlineFormValidate.hideWarningBox("row_1");
			$(triggeringVariable).addClass('validated').removeClass('has_error');
		}
}



function checkHomePhoneNumberPayment(warningOffset) {
	var triggeringVariable = "#home_phone";
	$(triggeringVariable).addClass("tested");
		
		if ($("select[name=country]").val() == "United Kingdom")
		{
			var homePhoneCheck = inlineFormValidate.checkField("home_phone", inlineFormValidate.phoneRegExp, 1);
		} else {
			var homePhoneCheck = inlineFormValidate.checkField("home_phone", inlineFormValidate.textBoxRegExp, 1);
		}
		
				
			if (homePhoneCheck !== 0)
			{
				inlineFormValidate.showWarningBox("row_2","Please enter a valid phone number","home_phone",warningOffset);
				$(triggeringVariable).addClass('has_error').removeClass('validated');
			} else {
				inlineFormValidate.hideWarningBox("row_2");
				$(triggeringVariable).addClass('validated').removeClass('has_error');
			}
}

function checkTandC(warningOffset)
{
	if (!$("#accept_tc:checked").val())
	{
		$("#accept_tc").addClass('has_error');
		inlineFormValidate.showWarningBox("row_11","Please confirm you accept our terms and conditions","accept_tc",warningOffset);
	} else {
		$("#accept_tc").removeClass('has_error');
		inlineFormValidate.hideWarningBox("row_11");
	}
}

function checkAddressPayment(warningOffset) {
		$("#address_1").addClass("tested");
		$("#address_2").addClass("tested");
		$("#address_3").addClass("tested");
		
		var address1Check = inlineFormValidate.checkField("address_1", inlineFormValidate.textBoxRegExp, 1);
		var address2Check = inlineFormValidate.checkField("address_2", inlineFormValidate.textBoxRegExp, 1);
		var address3Check = inlineFormValidate.checkField("address_3", inlineFormValidate.textBoxRegExp, 1);
				
		if ((address1Check == 1) && (address2Check == 1) && (address3Check == 1))
		{
			inlineFormValidate.showWarningBox("row_7","Please enter your company&rsquo;s address","address_1",warningOffset);
			$("#address_1").addClass('has_error').removeClass('validated');
			$("#address_2").addClass('has_error').removeClass('validated');
			$("#address_3").addClass('has_error').removeClass('validated');
		} else {
			inlineFormValidate.hideWarningBox("row_7");
			$("#address_1").removeClass('has_error');
			$("#address_2").removeClass('has_error');
			$("#address_3").removeClass('has_error');
			
			if ($("#address_1").val() !== "") {
				$("#address_1").addClass('validated');
			}
			if ($("#address_2").val() !== "") {
				$("#address_2").addClass('validated');
			}
			if ($("#address_2").val() !== "") {
				$("#address_2").addClass('validated');
			}
		}
}

function checkTownPayment(warningOffset) {
	var triggeringVariable = "#town";
	$(triggeringVariable).addClass("tested");
		
		var townCheck = inlineFormValidate.checkField("town", inlineFormValidate.textBoxRegExp, 1);
				
		if (townCheck !== 0)
		{
			inlineFormValidate.showWarningBox("row_8","Please enter your company&rsquo;s town","town",warningOffset);
			$(triggeringVariable).addClass('has_error').removeClass('validated');
		} else {
			inlineFormValidate.hideWarningBox("row_8");
			$(triggeringVariable).addClass('validated').removeClass('has_error');
		}
}

function checkPostcodePayment(warningOffset) {
	var triggeringVariable = "#postcode";

	$(triggeringVariable).addClass("tested");
		
		var townCheck = inlineFormValidate.checkField("town", inlineFormValidate.textBoxRegExp, 1);
		
		if ($("select[name=country]").val() == "United Kingdom")
		{
			var postcodeCheck = inlineFormValidate.checkField("postcode", inlineFormValidate.postcodeRegExp, 1);
		} else {
			var postcodeCheck = inlineFormValidate.checkField("postcode", inlineFormValidate.textBoxRegExp, 1);
		}
		
				
		if (postcodeCheck !== 0)
		{
			inlineFormValidate.showWarningBox("row_9","Please enter your company&rsquo;s postcode","postcode",warningOffset);
			$(triggeringVariable).addClass('has_error').removeClass('validated');
		} else {
			inlineFormValidate.hideWarningBox("row_9");
			$(triggeringVariable).addClass('validated').removeClass('has_error');
		}
}

function checkPostcodeCard(warningOffset) {
	var triggeringVariable = "#postcode";

	$(triggeringVariable).addClass("tested");
		
		var townCheck = inlineFormValidate.checkField("town", inlineFormValidate.textBoxRegExp, 1);
		var postcodeCheck = inlineFormValidate.checkField("postcode", inlineFormValidate.postcodeRegExp, 1);
				
		if (postcodeCheck !== 0)
		{
			inlineFormValidate.showWarningBox("row_9","Please enter the postcode the card you are paying with is registered to","postcode",warningOffset);
			$(triggeringVariable).addClass('has_error').removeClass('validated');
		} else {
			inlineFormValidate.hideWarningBox("row_9");
			$(triggeringVariable).addClass('validated').removeClass('has_error');
		}
}

function checkCCTypePayment(warningOffset) {
	$("#cctype").addClass("tested");
		
		var ccCheck = inlineFormValidate.checkDropDown("cctype", "", 1);
				
		if (ccCheck !== 0)
		{
			inlineFormValidate.showWarningBox("row_5","Please enter the card type","cctype",warningOffset);
		} else {
			inlineFormValidate.hideWarningBox("row_5");
		}
		
		if ($("#ccissue").hasClass("tested")) 
		{	
 			checkIssuePayment(300);
		}
}

function checkCCNumberPayment(warningOffset) {
		var triggeringVariable = "#ccnumber";
		$(triggeringVariable).addClass("tested");
		
		var ccNumCheck = inlineFormValidate.checkCardNumberField("ccnumber", 1);
		
		if (ccNumCheck !== 0)
		{
			inlineFormValidate.showWarningBox("row_6","Please enter a valid card number","ccnumber",warningOffset);
			$(triggeringVariable).addClass('has_error').removeClass('validated');
		} else {
			inlineFormValidate.hideWarningBox("row_6");
			$(triggeringVariable).addClass('validated').removeClass('has_error');
		}
}


function checkSecCodePayment(warningOffset) {
		var triggeringVariable = "#securitycode";
		$(triggeringVariable).addClass("tested");
				
		var ccSecCode = inlineFormValidate.checkField("securitycode", inlineFormValidate.secCodeRegExp, 1);
		
		if (ccSecCode !== 0)
		{
			inlineFormValidate.showWarningBox("row_7","Please enter a valid security code","securitycode",warningOffset);
			$(triggeringVariable).addClass('has_error').removeClass('validated');
		} else {
			inlineFormValidate.hideWarningBox("row_7");
			$(triggeringVariable).addClass('validated').removeClass('has_error');
		}

}


function expiryMonthPayment(warningOffset) {
	$("#month").addClass("tested");
		
		var monthCheck = inlineFormValidate.checkDropDown("month", "", 1);
		var yearCheck = inlineFormValidate.checkDropDown("year", "", 1);
		
		if ($("#year").hasClass("tested")) {
			if ((monthCheck !== 0) || (yearCheck !== 0))
			{
				inlineFormValidate.showWarningBox("row_8","Please enter the expiry date","year",warningOffset);
			} 
			
			if ((monthCheck === 0) && (yearCheck === 0)) {
				inlineFormValidate.hideWarningBox("row_8");
			}
		}
}


function expiryYearPayment(warningOffset) {
	$("#year").addClass("tested");
		
		var monthCheck = inlineFormValidate.checkDropDown("month", "", 1);
		var yearCheck = inlineFormValidate.checkDropDown("year", "", 1);
		
		if ($("#month").hasClass("tested")) {		
			if ((monthCheck == 1) || (yearCheck == 1))
			{
				inlineFormValidate.showWarningBox("row_8","Please enter the expiry date","year",warningOffset);
			} 
			
			if ((monthCheck === 0) && (yearCheck === 0)) {
				inlineFormValidate.hideWarningBox("row_8");
			}
		}
}

function checkIssuePayment(warningOffset) {
	
	$("#ccissue").addClass("tested");
		
	if (($("#cctype option:selected").val() == "Switch") || ($("#cctype option:selected").val() == "Maestro")) {
		
		var issueCheck = inlineFormValidate.checkField("ccissue", inlineFormValidate.issueRegExp, 1);
				
		if (issueCheck !== 0)
		{
			inlineFormValidate.showWarningBox("row_8","Please enter your card&rsquo;s issue number","ccissue",warningOffset);
		} else {
			inlineFormValidate.hideWarningBox("row_8");
		}
		
	} else {
			inlineFormValidate.hideWarningBox("row_8");
	}
	
}



function checkDonationAmount(warningOffset)
{
	$("#donation_amount").addClass("tested");

	var cardAmount = $("input[name=card_amount]:checked").val();
	var donationAmount = jQuery.trim($("#donation_amount").val());	
	
	if (isNaN(donationAmount))
	{
		inlineFormValidate.showWarningBox("row_don","Please enter only numbers","donation_amount",warningOffset);
		$("#donation_amount").addClass('has_error').removeClass('validated');
	} else {
		
		if ((cardAmount == 1) && (donationAmount < 50))
		{
			inlineFormValidate.showWarningBox("row_don","For this amount of cards, we ask for a minimum donation of &pound;50","donation_amount",warningOffset);
			$("#donation_amount").addClass('has_error').removeClass('validated');
		} 
		else if ((cardAmount == 2) && (donationAmount < 200)) 
		{
			inlineFormValidate.showWarningBox("row_don","For this amount of cards, we ask for a minimum donation of &pound;200","donation_amount",warningOffset);
			$("#donation_amount").addClass('has_error').removeClass('validated');
		}
		else if ((cardAmount == 3) && (donationAmount < 400)) 
		{
			inlineFormValidate.showWarningBox("row_don","For this amount of cards, we ask for a minimum donation of &pound;400","donation_amount",warningOffset);
			$("#donation_amount").addClass('has_error').removeClass('validated');
		} else {
			inlineFormValidate.hideWarningBox("row_don");
			$("#donation_amount").addClass('validated').removeClass('has_error');
		}
		
	}
	

}

function checkEmailPayment(warningOffset) {
	var triggeringVariable = "#email_address";
	$(triggeringVariable).addClass("tested");
		
		var emailCheck = inlineFormValidate.checkField("email_address", inlineFormValidate.emailRegExp, 1);
					
		if (emailCheck === 0) {
			inlineFormValidate.hideWarningBox("row_email");
			$(triggeringVariable).addClass('validated').removeClass('has_error');
			
		} else {
			inlineFormValidate.showWarningBox("row_email","Please enter a valid email address","email_address",warningOffset);
			$(triggeringVariable).addClass('has_error').removeClass('validated');

		}
}

function checkCharacterCount(field,remainingText,charLimit)
{
	var enteredText = $("#" + field).val();
	var enteredTextLength = enteredText.length;
	
	if (enteredTextLength < charLimit)
	{
		$("#" + remainingText + " span").html(charLimit - enteredTextLength);
		$("#" + remainingText).removeClass("warning_colour");
	}
	else
	{
		$("#" + field).val(enteredText.substr(0,charLimit));
		$("#" + remainingText + " span").html("0");
		$("#" + remainingText).addClass("warning_colour");
	}
}


function checkAllFieldsPayment() {
	
	$("input,select").addClass("tested");
	
	checkNamePayment(5480);
	checkPostcodeCard(480);
	checkCCTypePayment(260);
	checkCCNumberPayment(480);
	checkSecCodePayment(300);
	expiryMonthPayment(300);
	expiryYearPayment(300);
	checkIssuePayment(300);
	
	
	if ($(".warning_holder").length > 0) {
		$("body").scrollTo(500);
		return false;
	} else {
	
		$("input,textarea").each(function(){
		
			if ($(this).val() == $(this).attr("placeholder"))
			{
				$(this).val("");
			}
		
		});
	
		return true;
		
	}
	
}




function checkCustomFields1()
{
	$(".warning_holder").remove();

	checkSenderName(340);
	checkLogoUploaded(320);
		
	if ($(".warning_holder").length > 0)
	{
		return false;
	}
		
}

function checkCustomFields2()
{
	$(".warning_holder").remove();

	checkFirstNameSender(660);
	checkLastNameSender(660);
	checkEmailSender(660);
	checkHeadlines(380,"flash_var1");
	checkHeadlines(380,"flash_var2");
	checkHeadlines(380,"flash_var3");
	
	if ($(".warning_holder").length > 0)
	{
		return false;
	}
		
}

function checkCustomFields3()
{
	checkFirstNameSender(660);
	checkLastNameSender(660);
	checkEmailSender(660);
	
	if ($(".warning_holder").length > 0)
	{
		return false;
	}

}

function updateBeaverPreview()
{
	$("[rel=" + $(this).attr("id") + "]").html($(this).val());
	Cufon.replace("[rel=" + $(this).attr("id") + "]");
	$("#message").val($("#card_address_1").val() + "\n" + $("#card_address_2").val() + "\n" + $("#card_address_3").val() + "\n" + $("#card_address_4").val() + "\n" + $("#card_address_5").val());
}



function init_home()
{
	buildCarousel("card_picker_container_home");
	bindFancyboxPreview(0);
	$("#banner_login a").bind("click",showLoginBox);
}

function init_step_1()
{	
	//What is CSV
	$("#csv_info_link").fancybox({ 'overlayShow' : true,
					'overlayColor' : '#000',
					'overlayOpacity' : 0.7,
					'scrolling' : 'no',
					'titleShow' : false
	});
	
	//Logo info
	$("#logo_info_link").fancybox({ 'overlayShow' : true,
					'overlayColor' : '#000',
					'overlayOpacity' : 0.7,
					'scrolling' : 'no',
					'titleShow' : false
	});
	
	//Donation amount
	$("#card_amounts input").each(function(){
		$(this).bind("change",function(){
		
			inlineFormValidate.hideWarningBox("row_0");
			$("#more_1500").removeClass('has_error');
		
			if ($(this).val() == 1)
			{
				$(".form_note strong").html("&pound;50");
			} 
				else if ($(this).val() == 2)
			{
				$(".form_note strong").html("&pound;200");
			}
				else if ($(this).val() == 3)
			{
				$(".form_note strong").html("&pound;400");
			}
		
		
			if ($("#donation_amount").hasClass("tested"))
			{
				checkDonationAmount(590);
			}
		});
	});
	
	//Login form...
	$("#log_in_email_address,#log_in_email_password").bind("focus",function(){
		$("#log_in_email_address, #log_in_email_password").removeClass("has_error");
		$(".login_warning").slideUp();
	});
	
	
	$("#forgotten_password_link").bind("click",forgotPasswordBox);
	
	
	//Donation amount
	$("#donation_amount").bind("blur",function(){checkDonationAmount(590);});
	
	//First name
	$("#first_name").bind("blur",function(){checkFirstNameSender(660);});

	//Last name
	$("#last_name").bind("blur",function(){checkLastNameSender(660);});
	
	//Title
	$("#title").bind("blur, change",function(){checkTitleSender(660);});
	
	//Home phone
	$("#home_phone").bind("blur",function(){ checkHomePhoneNumberPayment(480);});
	
	//Email
	$("#email_address").bind("blur",function(){checkEmailSender(480);});
	
	$("#password").bind("blur",function(){checkPassword(480);});
	$("#confirm_password").bind("blur",function(){checkPasswordConfirm(480);});
	
	//Company name
	$("#company_name").bind("blur",function(){ checkCompanySender(480);});
	
	//Address
	$("#address_1").bind("blur",function(){ checkAddressPayment(480);});
	$("#address_2").bind("blur",function(){ checkAddressPayment(480);});
	$("#address_3").bind("blur",function(){ checkAddressPayment(480);});
	
	//Town
	$("#town").bind("blur",function(){ checkTownPayment(480);});
	
	//Postcode
	$("#postcode").bind("blur",function(){ checkPostcodePayment(325);});
	
	//T&Cs
	$("#accept_tc").bind("change",function(){ checkTandC(565);});
	
	$("#set_up_account_form").bind("submit",function(){
		_gaq.push(['_linkByPost', this]);
	
		$("input,textarea").each(function(){
		
			if ($(this).val() == $(this).attr("placeholder"))
			{
				$(this).val("");
			}
		
		});
	
		checkDonationAmount(590);
		checkFirstNameSender(660);
		checkLastNameSender(660);
		checkTitleSender(660);
		checkHomePhoneNumberPayment(480);
		checkEmailSender(480);
		checkPassword(480);
		checkPasswordConfirm(480);
		checkCompanySender(480);
		checkAddressPayment(480);
		checkTownPayment(480);
		checkPostcodePayment(325);
		checkTandC(565);
		cardAmountSelected(540);
		
		if ($(".warning_holder").length > 0) {
			$("body").scrollTo(500);
			return false;
		} else {
			_gaq.push(['_linkByPost', this]);
			return true;
	
		}

	});
}

function init_step_2()
{
	//Name
	$("#name").bind("blur",function(){ checkNamePayment(480);});
	
	$("#postcode").bind("blur",function(){ checkPostcodeCard(480);});
							
	//Card type
	$("#cctype").bind("change",function(){ checkCCTypePayment(260);}).bind("blur",function(){ checkCCTypePayment(260);});
	
	//Card number
	$("#ccnumber").bind("blur",function(){ checkCCNumberPayment(480);});

	//Card number
	$("#securitycode").bind("blur",function(){ checkSecCodePayment(300);});
	
	//Expiry month
	$("#month").bind("change",function(){ expiryMonthPayment(300);}).bind("blur",function(){ expiryMonthPayment(300);});
	
	//Expiry year
	$("#year").bind("change",function(){ expiryYearPayment(300);}).bind("blur",function(){ expiryYearPayment(300);});	
	
	//Issue date
	$("#ccissue").bind("blur",function(){ checkIssuePayment(300);});

	//Form submit
	$("#make_a_donation").bind("submit",checkAllFieldsPayment);
	
	//What is the security code
	$("#what_is_security_code").fancybox({ 'overlayShow' : true,
					'overlayColor' : '#000',
					'overlayOpacity' : 0.7,
					'scrolling' : 'no',
					'titleShow' : false
	});
	

}

function init_step_3()
{
	//Set an absolute height on the picker
    $("#inner_shadow").css("height",$("#inner_shadow").height() + "px");
    
    bindPickerButtons();
	bindFancyboxPreview(1);
	bindPopupDescriptions();
}

function init_step_4()
{					
	bindFancyboxPreview(2);	
}

function init_form_1()
{
	//First name
	$("#personalisation_from_name").bind("blur",function(){checkSenderName(340);});
	
	//Email
	$("#message").bind("keyup",function(){checkCharacterCount("message","remaining_characters",200);}).keyup();
	$("#customise_card_form").bind("submit",checkCustomFields1);
	bindUploadImage("#choose_image_button");

}

function get_full_name()
{
	$("#flash_var1").val($("#first_name").val() + " " + $("#last_name").val());
}

function init_form_2()
{
	//First name
	$("#personalisation_from_name").bind("blur",function(){checkSenderName(340);});
	
	$("#flash_var1").bind("keyup",function(){checkCharacterCount("flash_var1","remaining_characters_hl1",20);}).keyup();
	
	//Email
	$("#message").bind("keyup",function(){checkCharacterCount("message","remaining_characters",200);}).keyup();
	$("#customise_card_form").bind("submit",checkCustomFields1);
	bindUploadImage("#choose_image_button");

}

function init_form_3()
{
	//First name
	$("#personalisation_from_name").bind("blur",function(){checkSenderName(340);});
	
	//Email
	$("#message").bind("keyup",function(){checkCharacterCount("message","remaining_characters",200);}).keyup();
	$("#customise_card_form").bind("submit",checkCustomFields1);
	bindUploadImage("#choose_image_button");
	
	$("#instructions_link").bind("click",function()
	{
		if ($("#uploaded_logo").val() !== "")
		{
			$(this).attr("href",$(this).attr("href") + "?logo=" +$("#uploaded_logo").val());
		}
		
	});

}



function init_step_5()
{
	
	//Upload CSV
	$("#upload_csv_button").bind("click",uploadCSV);
	
	emailRecipients = 5;

	$("#submit_form_maincol").hide();
	//What is CSV
	$("#csv_info_link").fancybox({ 'overlayShow' : true,
					'overlayColor' : '#000',
					'overlayOpacity' : 0.7,
					'scrolling' : 'no',
					'titleShow' : false
	});
	
	//Email delivery explanation
	$("#email_delivery_explanation").live("click",function(){
		$("#email_delivery_explanation_text").slideDown();
		return false;
	});	
	
	$("#main_content_column").css("min-height",($("#main_content_column").height() + 10) + "px");
	
	$("#add_more_recipients").bind("click",addMoreRecipients);
	
	
	//batch
	$("#batch_send").bind("click",function(){
		$("#csv_send_options").slideDown();
		$("#recipient_list").slideUp();
		$("#add_more_recipients,#submit_form_maincol").fadeOut();
		
		
		//Hide warnings
		$(".warning_holder").fadeOut(function(){
			$(this).remove();
		});
	});
	
	//email
	$("#send_to_email").bind("click",function(){
		$("#recipient_list").slideDown();
		$("#csv_send_options").slideUp();
		$("#add_more_recipients,#submit_form_maincol").fadeIn();
		//Hide warnings
		$(".warning_holder").fadeOut(function(){
			$(this).remove();
		});
	});
	
	//print
	$("#print_link").bind("click",function(){
		$("#recipient_list").slideUp();
		$("#csv_send_options").slideUp();
		$("#add_more_recipients").fadeOut();
		$("#submit_form_maincol").fadeIn();
		
		//Hide warnings
		$(".warning_holder").fadeOut(function(){
			$(this).remove();
		});
	});
	
	//submit
	$("#card_recipient_form").bind("submit",function(){
		
		if ($("#send_to_email").attr("checked") === true)
		{
			if (checkEmailRecipients() === 0)
			{
				return false;
			}
			else
			{
				return true;			
			}
		}
	});
	
	//On blur...
	$(".recipient_name_col input").each(function(){
		$(this).bind("blur",function() {
			testEmailRecipient($(this).attr("data-index"),"name");
		});
	});
	
	$(".recipient_email_col input").each(function(){
		$(this).bind("blur",function() {
			testEmailRecipient($(this).attr("data-index"),"email");
		});
	});
	
	bindFancyboxPreview(3);
	
	if ($('#card_preview_box').length > 0) {
		AutoPlayCard();
	}
	
}

function init_step_6()
{
	
}

function init_payment()
{

	//Replace fields if no value present
	if ((jQuery.trim($("#inputamount").val()) === "") || (jQuery.trim($("#email_address").val()) === "") || (!$("#inputamount").val()) || (!$("#email_address").val()))
	{
		$("#email_area,#inputamount,#email_address").remove();
		$("#donate_area").addClass("final_question");
		$("#donate_field").html('<strong style="position: relative;bottom: 6px; padding-right: 5px;">&pound;</strong><span class="input_wrap"><input class="form_text_field js_fields" type="text" id="inputamount" name="inputamount" /></span>');
		$("#phone_area").removeClass("final_question").after('<div class="question clearfix final_question"><div class="question_label"><label for="email_address">Email <span class="required_field">*</span></label></div><div class="question_input" id="address_block"><span class="input_wrap"><input class="form_text_field address_field js_fields" type="text" id="email_address" name="email_address" value="" /></span></div></div>');
		$("#donation_token").val("");
		
		//Email
		$("#email_address").bind("blur",function(){ checkEmailPayment(590);});
		//Email
		$("#inputamount").bind("blur",function(){ checkDonationAmount(370);});
	}
	
	
	//Name
	$("#name").bind("blur",function(){ checkNamePayment(590);});
							
	//Home phone
	$("#home_phone").bind("blur",function(){ checkHomePhoneNumberPayment(590);});

	//Mobile phone
	$("#mobile_phone").bind("blur",function(){ checkMobilePhoneNumberPayment(590);});
	
	//Address
	$("#address_1").bind("blur",function(){ checkAddressPayment(590);});
	$("#address_2").bind("blur",function(){ checkAddressPayment(590);});
	$("#address_3").bind("blur",function(){ checkAddressPayment(590);});
	
	//Town
	$("#town").bind("blur",function(){ checkTownPayment(590);});
	
	//Postcode
	$("#postcode").bind("blur",function(){ checkPostcodePayment(590);});
	
	//Card type
	$("#cctype").bind("change",function(){ checkCCTypePayment(240);}).bind("blur",function(){ checkCCTypePayment(240);});
	
	//Card number
	$("#ccnumber").bind("blur",function(){ checkCCNumberPayment(590);});

	//Card number
	$("#securitycode").bind("blur",function(){ checkSecCodePayment(590);});
	
	//Expiry month
	$("#month").bind("change",function(){ expiryMonthPayment(285);}).bind("blur",function(){ expiryMonthPayment(285);});
	
	//Expiry year
	$("#year").bind("change",function(){ expiryYearPayment(285);}).bind("blur",function(){ expiryYearPayment(285);});	
	
	//Issue date
	$("#ccissue").bind("blur",function(){ checkIssuePayment(590);});

	//Form submit
	$("#make_a_donation").bind("submit",checkAllFieldsPayment);
	
	//What is the security code
	$("#what_is_security_code").fancybox({ 'overlayShow' : true,
					'overlayColor' : '#000',
					'overlayOpacity' : 0.7,
					'scrolling' : 'no',
					'titleShow' : false
							
	});
	
	calculateGiftAid();

}

function supports_video() {
  return !!document.createElement('video').canPlayType;
}


//Check success of SWF object
function checkStatus(e)
{
	if (e.success === false)
	{
	
		if (supports_video())
		{
		
			window.location = $("#html5_address").val();
		
		} else {
			$("#noflash_nohtml5").fadeIn("slow");
		}
	}
}

$(document).ready(function(){

	Cufon.replace('h1,h2,.payment_fieldset legend,#strap_title,#body_copy_area legend');
	

	//Remove warning box
	$("#warning").remove();
	
	//Hover styles
	$(".submit_form_button").hover(function(){
			$(this).children().css("text-decoration","underline");
		},function(){
			$(this).children().css("text-decoration","none");
		}
	);

	addPlaceholders();
	
});
