$(document).ready(function() {
	
	//email verification
	$('#notify_email_address').keyup(function(data){
		
		var email = (this).value;
		
		$.post("includes/inc.valid_email.php", {email: email}, function(data){

			if(data == 'false')
			{
				$("#box_incorrect_email_address").html('<font color=\'red\'>Please provide correct email address</font>');
			}
			else
			{
				$("#box_incorrect_email_address").html('')
			}
		});
	});

	/* Gift wrap */
	$('input.gift_wrap').click(function() {
		update_gift_wrap(this);
	});
	
	$('textarea.message').data('max_length',250);
	$('textarea.message').prev("label").find("span.char_count").html($('textarea.message').data('max_length'));
	
	// textarea character count
	$("textarea.message").keypress(function(event) {
		
		// get current count
		charCount = $(this).val().length;
		charCount += 1;
		
		if (charCount >= $(this).data('max_length'))
		{
			if(event.keyCode != 46 && event.keyCode != 8)
			{
				event.preventDefault();
			}
			else if(event.keyCode >= 37 && event.keyCode <= 40)
			{
				event.preventDefault();
			}
		}
		else
		{
			remaining = $(this).data('max_length') - (charCount);
			
			if(!remaining)
			{
				remaining = '0';
			}
			$(this).prev("label").find("span.char_count").html(remaining);
		}
	});
	
	/* Participant form */
	// hide participant fields
	$("#participant_form div.row div.options input#not_gift").each(function() {
		
		if($(this).attr("checked"))
		{
			container = $(this).parent().parent();
			
			container.nextAll("div.row").css({display:"none"});
			container.nextAll("div.title").css({display:"none"});
			container.nextAll("div.mobile").css({display:"block"});
			container.find(".instruction span.you").html("you")
			container.find(".instruction span.your").html("your")
		}
	});
	$("#participant_form div.row div.options input#not_gift").click(function() {
		
		if($(this).attr("checked"))
		{
			container = $(this).parent().parent();
			container.nextAll("div.row").css({display:"none"});
			container.nextAll("div.title").css({display:"none"});
			container.nextAll("div.mobile").css({display:"block"});
			container.find(".instruction span.you").html("you")
			container.find(".instruction span.your").html("your")
		}
	});
	
	// participant form toggle
	$("#participant_form div.row div.options #is_gift:first").click(function() {
		
		container = $(this).parent().parent();
		container.nextAll("div.row").toggle();
		container.nextAll("div.title").toggle();
		container.nextAll("div.mobile").css({display:"block"});
		
		container.parent().find("div.instruction span.you").html("the participant")
		container.parent().find("div.instruction span.your").html("their")
	});
	
	/* Payment form */
	// protx form card selection
	$("div.select_card_type label").click(function() {
		
		$(this).find("input").attr("checked","checked");
		$(this).fadeTo(1,1);
		$(this).siblings().fadeTo(1,0.20);
		
		if($(this).attr('for') == 'amex') {
			$('#cv2_length').html(4);
		}
		else {
			$('#cv2_length').html(3);
		}
		
	});
	
	/* Checkout Details Form */
	if($("#checkout_details").length) {
		
			/* Delivery form */
			
			// set state after reloading page
			if($('#delivery_is_different').attr("checked")) {
				$("#delivery_address").show();
				
				if($('#use_saved_delivery_address').attr("checked")) {
					$("#blank_delivery_address").hide();
					$("#saved_delivery_addresses").show();
				};
			};

			// delivery address toggles
			$("#delivery_is_different").click(function(event) {
			
			if(event.target.checked) {
				$("#delivery_address").slideDown();
			}
			else{
				$("#delivery_address").slideUp();
			}
		});
		
		$("#use_saved_delivery_address").click(function(event) { 
			
		if (event.target.checked) {
		 	$("#blank_delivery_address").slideUp();
		 	$("#saved_delivery_addresses").slideDown();
		 }
		 else {
		 	$("#blank_delivery_address").slideDown();
		 	$("#saved_delivery_addresses").slideUp();
		 }			
		});
		
		if($('#checkout_details').length) {
			
			$('#checkout_details').submit(checkout_form);
			
			// disable the continue button until the newsletter is confirmed
//			$('#cart_continue input').attr('disabled',true).addClass('disabled');
			
			
			$('#close_shade').live('click',function() {
				$(this).parents('#shade_holder').hide();
				$(this).parents('#shade_holder').find('#shade_info_box_1').empty();
			});
			
			$('#checkout_newsletter_link').click(function(event) {
				event.preventDefault();
				$('#shade_holder').show().fadeTo(0,.90).css({
					background:'#ccc',
					height:1300
				});
				
				var shade_content =	'<a id="close_shade">Close <img src="images/icon-delete.png" /></a>';
				shade_content += "<iframe src=\"" + $(this).attr('href') + "\"></iframe>";

				$('#shade_info_box_1').show().fadeTo(0,100).empty();
				$('#shade_info_box_1').css({
					width:700,
					height:800,
					overflow:'visible',
					border:'1px solid red',
					background:'#FFF'
				}).append(shade_content);
				
				$('#shade_info_box_1 iframe').css({
					height:'100%'
				})
//				window.scrollTo(0,0);
				$.newsletter_confirmed = true;
				$('#newsletter_caution').fadeOut();
			});
		}
		
		$('#newsletter_opt_out').click(function() {
			$.newsletter_confirmed = true;
			$('#newsletter_caution').fadeOut();
		})

		/* Event handlers */
		$("#b_email").keyup(function() {
			check_account($(this));
		});
		$("#b_email").change(function() {
			$(this).trigger('keyup');
		});
		
		$('#lost_password').click(function(event) {
			event.preventDefault();
			send_new_password($("#b_email").val())
		});	
		
		$("#claim_code").change(check_voucher_code);
		$("#claim_code").keyup(check_voucher_code);
	}
	
	/* Cart Quantity options */
	if($('#cart_holder').length) {
	
		$('.item_quantity select').change(updateQty);
		$('.child_selector select').change(updateChild);
	}
	
	/* Fast Nav Advanced search */
	search_inputs = $("#advanced_search input[type='text']");
	search_inputs.each(function() {
		$(this).data('default',$(this).val());
	});
	
	search_inputs.focus(function() {
		if($(this).val() == $(this).data('default')) {
			$(this).val("");
		}
	});
	
	search_inputs.blur(function() {
		if(!$(this).val().length) {
			$(this).val($(this).data('default'));
		}
	});
	
	//Disable last 'Continue button' when credit card details has been provided
	//to disable 'double' post.
	$('#finalise_payment_button').click(function(event){
		$(this).attr('disabled','disabled');
		document.ready.submit();	
	});	
	
	/* Disable and animate shop buttons on click */
	$('#cart_continue input').click(function(event) {
		
		if($(this).interval) {
			clearInterval($(this).interval);
		}
		
		$(this).val('Processing');
		
		// re-enable to button after 10 seconds
		interval = setInterval(function() {
			$('#cart_continue input').removeAttr('disabled');
			$('#cart_continue input').val('Continue');
			clearInterval(interval);
			
		},10000);
	});
	
	// Order print
	$('#print_order').click(function() {
		window.print();
	});
	
});

function checkout_form(event) {

	form = $("#"+event.target.id);

	if($("#delivery_is_different").attr("checked")	&& !$("#use_saved_delivery_address").attr("checked")) {
		inputs = form.find(":input.required");
	}
	else {
		inputs = form.find(":input.required.billing"); 
	}
	
	inputs.each(function() {
		
		if(!this.value) {
			$(this).siblings("span.warning").fadeIn();
			$(this).siblings("img.caution_img").fadeIn();
			$(this).addClass('error');
			event.preventDefault();
			reset_submit_button()
		}
		else {
			$(this).siblings("span.warning").fadeOut();
			$(this).siblings("img.caution_img").fadeOut();
			$(this).removeClass('error');
		}
	});
	
	if($("#terms_yes").length) {
		if(!$("#terms_yes").attr("checked")) {
			$("#terms_yes").parents("div:first").find("span.warning").fadeIn();
			event.preventDefault();
			reset_submit_button()
		}
		else {
			$("#terms_yes").parents("div:first").find("span.warning").fadeOut();
		}
	}
	
	if(!$.newsletter_confirmed && $('#checkout_newsletter_link').length) {
		event.preventDefault();
		$('#newsletter_caution').fadeIn();
		$('#checkout_newsletter_link').fadeOut(500,function() {
			$(this).fadeIn(400);
		});
	}
	
}
function reset_submit_button() {
	$('#cart_continue input').removeAttr('disabled');
	$('#cart_continue input').val('Continue');
}

function select_product(product_id)
{
	sku_code=document.add_to_cart.sku.options[document.add_to_cart.sku.selectedIndex].value;
	item_quantity=document.add_to_cart.qty.options[document.add_to_cart.qty.selectedIndex].value;

	document.location.href='?page=shop&pid='+product_id+'&action=add_item&sku='+sku_code+'&qty='+item_quantity;
}

function showHideDel(objToSwitch) {
	if (document.getElementById(objToSwitch).style.display == 'none') document.getElementById(objToSwitch).style.display = 'block';
	else document.getElementById(objToSwitch).style.display = 'none';
}

function checkTicks(objToCheck) {
	if (document.getElementById(objToCheck).checked == "true") {
		document.getElementById(objToCheck).style.display = 'block';
	} else {
		document.getElementById(objToCheck).style.display = 'none';
		document.getElementById(objToCheck).checked = "false";
	}
}
// onLoad="checkTicks('inTheServices'); checkTicks('deliveryAddress')";

function update_order_type(order_type)
{
	window.location = '?page=shop&option=cart&action=update_del&type=' + order_type;
}
function update_gift_wrap(item)
{
	itemID = item.id;
	splitID = itemID.split('_');
	
	sku = splitID[1];
	
	window.location = '?page=shop&option=cart&action=update_gift&sku=' + sku;
}
function check_gift_options()
{
	valid = true;
	$("div.voucher div.row > :input").each(function() {

		
		if(this.id.indexOf('message') == -1)
		{
			if(this.value == "")
			{
				$(this).addClass("caution")
				$(this).nextAll().css({display:"inline"});
				$(this).nextAll("span.example").css({
					display: "none"
				});
				
				valid = false;
			}
			else
			{
				$(this).removeClass("caution");
				$(this).nextAll().css({display:"none"});
				$(this).nextAll("span.example").css({
					display: "inline"
				});
			}
		}
	});
	
	return valid;
}
function check_voucher_code(event)
{
	//$ = jQuery.noConflict();
	if(event.keyCode == 17)
	{
		return false;
	}
	
	claim_code = event.target.value;
	
	// dont check partial entries
	if(claim_code.length < 14)
	{
		return false;
	}
	
	// check code is not already validated
	if($("#valid_claim_codes").val().length > 0) {
		if ($("#valid_claim_codes").attr("value").indexOf(claim_code) != -1) {
			// clear field error formatting
			$("#claim_code").css({
				border: "0px"
			})
			$("#claim_code").nextAll().css({
				display: "none"
			});
				
			return false;
		}
	}
	
	// check code on server
	$.get("ajax/index.php", {
		page: "shop",
		action: "voucher_code",
		code: claim_code
	}, function(amount) {

		if(amount == 'redirect')
		{
			window.location = "index.php";
		}
		
		if(amount > 0)
		{
			// clear field error formatting
			$("#claim_code").css({border:"0px"})
			$("#claim_code").nextAll("img").css({display:"none"});
			$("#claim_code").nextAll("span").css({display:"none"});
			
			validCodes = $("#valid_claim_codes").val();

			$("#list_claim_codes").addClass('visible');

			//add the claim code and amount to the table;
			codeHTML = "<tr><td>" + claim_code + "</td><td align=\"center\">&pound;" + amount +  "</td></tr>";
			
			$("#list_claim_codes").append(codeHTML);
			
			//append the claim code to the valid_claim_codes hidden field
			validCodes = $("#valid_claim_codes").val();
			
			if(validCodes.length==1)
			{
				validCodes = "";
			}
			validCodes +=  claim_code + "|";

			$("#valid_claim_codes").attr("value",validCodes);
			
			$("#claim_code").val('');
		}
		else
		{
			// mark field as invalid
			$("#claim_code").css({border:"2px solid #CC0033"})
			$("#claim_code").nextAll("img").css({display:"inline"});
			$("#claim_code").nextAll("span").css({display:"inline"});
			valid = false;
		}
	},
	'text');		
}
function fastnav_get_voucher_balance(event,claim_code)
{
	//$ = jQuery.noConflict();
	
	if(event.keyCode == 17)
	{
		return false;
	}

	if (claim_code.length < 14)
	{
		$("div.balance_holder span.balance").html('£' + 0);
		return false
	}
	
	// check code on server
	$.get("ajax/index.php", {
		page: "shop",
		action: "voucher_code",
		code: claim_code
	}, function(amount) {
		
		if(amount == 'redirect')
		{
			amount = 0;
		}
		
		$("div.balance_holder span.balance").html('£' + amount);
				
		$("#claim_code").val('');
	},
	'text');		
}
function remove_claim_code(code)
{
	validCodes = $("#valid_claim_codes").val();
	
	return false;
}

function updateChild(event) {
	
	el = $(event.target);
	
	item_id = el.attr('id').split('_')[1];
	new_sku = el.val();
	
	option = get_page_option();
	
	document.location.href='?page=shop&option=' + option + '&action=update_item&sku='+item_id+'&newsku='+new_sku;
	
}
function updateQty(event) {
	
	el = $(event.target);
	
	item_id = el.attr('id').split('_')[1];
	new_qty = el.val();
	
	option = get_page_option();
	
	document.location.href='?page=shop&option=' + option + '&action=update_item&sku='+item_id+'&qty='+new_qty;
}

function get_page_option() {
	
	params = document.location.href.split('&');
	params.shift();
	
	$.each(params,function() {
		if(this.indexOf('option') != -1) {
			option = this.split('=')[1];
		}
	});
	
	return option;
}
