// Helper functions
function format_currency(strValue)
{
	strValue = strValue.toString().replace(/\$|\,/g,'');
	dblValue = parseFloat(strValue);

	blnSign = (dblValue == (dblValue = Math.abs(dblValue)));
	dblValue = Math.floor(dblValue*100+0.50000000001);
	intCents = dblValue%100;
	strCents = intCents.toString();
	dblValue = Math.floor(dblValue/100).toString();
	if(intCents<10) {
		strCents = "0" + strCents;
	}
	for (var i = 0; i < Math.floor((dblValue.length-(1+i))/3); i++) {
		dblValue = dblValue.substring(0,dblValue.length-(4*i+3))+','+dblValue.substring(dblValue.length-(4*i+3));
	}
	return (((blnSign)?'':'-') + dblValue);
}
function generate_alert(message, message_class) {
	if($('#nabru_alert').length === 0) {
		// if the nabru custom alert element doesn't already exist, we create it.
		var alert = $('<div id="nabru_alert"></div>');
		$("body").append(alert);
	}
	$('#nabru_alert').html(message).removeClass().addClass(message_class)
					.css({'opacity': 1, 
					 'top': $(window).scrollTop() + ($(window).height()/2-$('#nabru_alert').height()/2), 
					 'left': ($(window).width()/2-$('#nabru_alert').width()/2) })
					.stop()
					.animate({ 
						opacity: 1
					}, 2500)
					.animate({ 
						opacity: 0.0,
						top: $(window).scrollTop() - $('#nabru_alert').height()
					}, 1500);
}

// Spare Parts
function toggle_display(container) {
	$('#' + container + '-parts').toggle();
}
function updatePartsTotal(form) {
	var total=0;	
	for (var i = 0; i < form.elements.length; i++)
    {
    	var e = form.elements[i];
      	if ( e.type == 'text')
      	{
      		var fielddesc=e.id.split("_");
      		if(fielddesc[0]=="quantity" && parseInt(e.value)>0)
      		{
      			var quantity=parseInt(e.value);
      			var pricefield="price-"+fielddesc[1];
      			var frontandbackfield="frontandback-"+fielddesc[1];
 				var pulldown=document.getElementById(frontandbackfield);
 				var percentage=100;
 				if(pulldown)
 				{
					var Item = pulldown.selectedIndex;
					Item = pulldown.options[Item].text;
					var myRegExp = /Front/;
					var matchPos1 = Item.search(myRegExp);
					var myRegExp = /Rear/;
					var matchPos2 = Item.search(myRegExp);
					if(matchPos1!=-1 || matchPos2!=-1)
					{
						percentage=50;
					}
				}     			
				var priceobject=document.getElementById(pricefield);
				var price=priceobject.innerHTML;
				price=price.substring(1);
				price=parseInt(price);
				price=price*(percentage/100);
				price=Math.ceil(price);
	      		total=total+(price*quantity);
      		}
		}
	}
	var totalfield=document.getElementById('totalcost');
	totalfield.innerHTML=total;
}

// Homepage
function homepage_slideshow_switch() {
    var active = $('div.slide.active');

    if (active.length === 0) { active = $('div.slide:last'); }
    var next = active.next().length ? active.next() : $('div.slide:first');

    //active.addClass('last-active');
    next.css({opacity: 0.0}).addClass('active').animate({opacity: 1.0}, 1000, function() { 
		active.removeClass('active last-active'); 
	});
}


function slideshow_switch() {
    var active = $('.slideshow img.active');

    if (active.length === 0) { active = $('.slideshow img:last'); }
    var next =  active.next().length ? active.next() : $('.slideshow img:first');

    active.addClass('last-active');
    next.css({opacity: 0.0}).addClass('active').animate({opacity: 1.0}, 1000, function() { active.removeClass('active last-active'); });
}

/* Basket functions */
function basket_update_values(result) {
	$('#basket_subtotal span.price').fadeOut('fast', function() { $(this).html('&pound;' + format_currency(result.basket_summary.total_price)).fadeIn('fast'); });
	$('#basket_items span').html(result.basket_summary.total_items);
	$('#basket_total span').html('&pound;' + format_currency(result.basket_summary.total_price));
}
function basket_update_quantity(item_id, result) {
	// Remove the basket item if our quantity hits 0
	if(result.response <= 0) {
		$('#basket_item_' + item_id).fadeOut('fast', function() { 
			$(this).remove();
			if($('div.basket_item').length == 0) {
				$('#basket_empty').fadeIn('slow');
				$('div.basket_extras').hide();
			}
		});
	} else {
		var quantity_text = $('#basket_item_' + item_id + ' span.quantity');
		quantity_text.fadeOut('fast', function() { $(this).html(result.response).fadeIn('fast'); });
	}
	basket_update_values(result);
}
/* End basket functions */

/* Delivery datepicker functions */
function datePickerDisableDates(date, blockDates, assembly) {
	date = new Date(date);
	// We only allow Sunday deliveries for assembly bookings
	if(0 && date.getDay() === 0) {
		return [((date.getDay() === 0) ? 0 : 1), ""];
	} else {
		// Does the date fall on a bank holiday?
		var i = 0;
		for(i = 0; i < bankHolidays.length; i++) {
			var bankHolidayDateArray 	= bankHolidays[i].split('-');
			var bankHolidayDate 		= new Date(bankHolidayDateArray[0], bankHolidayDateArray[1], bankHolidayDateArray[2]);
			if(date.getDate() == bankHolidayDateArray[2] && (date.getMonth()+1) == bankHolidayDateArray[1] && date.getFullYear() == bankHolidayDateArray[0]) {
				return [0, ""];
			} 
		}
		
		// Y-M-D
		// Check for other delivery related blockages
		for(i = 0; i < blockDates.length; i++) {
			var deliveryDateArray 		= blockDates[i].split('-');
			var deliveryDate 			= new Date();
			deliveryDate.setFullYear(bankHolidayDateArray[0], deliveryDateArray[1], deliveryDateArray[2]);
			if(date.getDate() == deliveryDateArray[2] && (date.getMonth()+1) == deliveryDateArray[1] && date.getFullYear() == deliveryDateArray[0]) {
				return [0, ""];
			}
		}
		return [1, ""];
	}
}		
function datePickerDisableNonAssemblyDates(date) {
	return datePickerDisableDates(date, standardDeliveryDays, false);
}
function datePickerDisableAssemblyDates(date) {
	return datePickerDisableDates(date, assemblyDeliveryDays, true);
}
/* End datepicker delivery functions */

/* Delivery functions */
function calculateDeliveryCost(method,toroom,toroomcost) {
	var optionPrice	= 0;
	if($('input[name=delivery_time]:checked').length > 0) {
		optionPrice = $('input[name=delivery_time]:checked').parent().find('div.price').html().replace('£', '').replace(',', '');		
	}
	var totalPrice = parseInt(optionPrice, 10);

    if(method=="free")
	{
		totalPrice=0;
	}
    if(toroom==1)
	{
		/* totalPrice=totalPrice+toroomcost; */
	}
	$('li#delivery_date_time div.total').html('+&pound;' + totalPrice);
	$('span#delivery_total_amount').html('&pound;' + totalPrice);
	
	var basketTotal = $('span#basket_total_amount').length > 0 ? parseInt($('span#basket_total_amount').html().replace('£', '').replace(',', ''), 10) : 0;
	var assemblyTotal = $('span#assembly_total_amount').length > 0 ? parseInt($('span#assembly_total_amount').html().replace('£', '').replace(',', ''), 10) : 0;
	var postcodeTotal = $('span#postcode_total_amount').length > 0 ? parseInt($('span#postcode_total_amount').html().replace('£', '').replace(',', ''), 10) : 0;
	var deliveryTotal = $('span#delivery_total_amount').length > 0 ? parseInt($('span#delivery_total_amount').html().replace('£', '').replace(',', ''), 10) : 0;
	$('span#order_total_amount').html('&pound;' + parseInt(basketTotal + assemblyTotal + postcodeTotal + deliveryTotal, 10));
}
/* End delivery functions */

/* Payment options */
function handleSameAsDeliveryOption() {
	if($('input[name=same_as_delivery]:checked').length > 0) {
		$('div.address_form.billing ul input, div.address_form.billing ul select').attr('readonly', 'readonly'); 
		$('div.address_form.shipping ul input, div.address_form.shipping ul select').each(function() {
			var altEl = $(this).attr('name').replace('shipping_', 'billing_');
			$('div.address_form.billing input[name=' + altEl + '], div.address_form.billing select[name=' + altEl + ']').val($(this).val());
		});
		$('div.address_form.billing').fadeOut('fast');
	} else {
		$('div.address_form.billing').fadeIn('fast');
		$('div.address_form.billing ul input, div.address_form.billing ul select').removeAttr('readonly');
	}
}
/*function fadePaymentOptions() {
	$('[name=payment_method]:not(:checked)').each(function() {
		$(this).next('img').animate({opacity: 0.25}, 750);
	});
	$('[name=payment_method]:checked').next('img').animate({opacity: 1}, 750);
}*/
/* End payment options */

function calculatePrice() {
	var new_price = parseInt($('input[name=base_price]').val());
	var extra_price = 0;
	var fabricCover = 0;
	var twoTone	= 0;
	var piping = 0;
	$('select :selected').each(function(i, val) {
		var selected_price = $(this).text().match(/\£([\d.,]+)/);
		if(selected_price !== null && selected_price.length !== 0) {
			var final_selected_price = selected_price[1];
			
			// Has the user chosen a fabric cover?
			var fabricCoverSelected = $(this).text().indexOf("EC: ",0);
	        var fabricCoverNoneSelected = $(this).text().indexOf("EC: None",0);
	        if(fabricCoverSelected != -1 && fabricCoverNoneSelected == -1) {
	        	fabricCover = 1;	
	        }
	
			// Has the user chosen a two-tone fabric
			var twoToneSelected = $(this).text().indexOf("TT: ", 0);
	        var twoToneNoneSelected = $(this).text().indexOf("TT: None", 0);
	        if(twoToneSelected != -1 && twoToneNoneSelected == -1) {
	        	twoTone = 1;
	        }
	        var pipingSelected = $(this).text().indexOf("Piping - Yes", 0);
	        if(pipingSelected != -1) {
	        	piping = 1;
	        }
			if(fabricCoverSelected != -1 && fabricCoverNoneSelected == -1) {
				if(piping) {
					var percentage = final_selected_price * (35/100);
					percentage = Math.floor(percentage);
					extra_price += percentage;
				}	
	        }
			new_price += parseInt(final_selected_price);
		} 
	});
	$('[name^=option2]').each(function(i, val) {
		var selected_price = $(this).val().match(/\£([\d.,]+)/);
		if(selected_price !== null && selected_price.length !== 0) {
			new_price += parseInt(selected_price[1]);
		} 
	});
	
	
	if(fabricCover && twoTone) {
    	new_price += 20
    }
	new_price += extra_price;
	
	return new_price;
}

//Document Ready
$(document).ready(function() {
	
	// lightboxes
	$('a.lightbox_trigger').fancybox({ overlayOpacity: 0.7 });
	
	// custom ie6 handling
	if ($.browser.msie && $.browser.version == '6.0') {
		$('#basket').click(function() {
			window.location.replace("/basket");
		})
	}
	
	//homepage
	if($('div.home_title_2').length !== 0) {
		setInterval( 'homepage_slideshow_switch()', 5000 );
	}
	
	//contact
	if($('#contact_form').length !== 0) {
		$('#contact_form').submit(function(e) {
			var name = $('[name=name]').val();
			var email = $('[name=email]').val();
			var message = $('[name=message]').val();
			if(name.length > 0 && name != '* Name' && email.length > 0 && email != '* Email' &&
				message.length > 0 && message != '* Your message') {
				$.ajax({  
					type: "POST",  
					url: "inc/ajax/contact.php",  
					data: $(this).serialize(),  
					success: function(data, text) {
						if(text != 'false') {
							$('#contact_form_container').fadeOut('fast', function() { $(this).html('<div class="success">Thank you, we\'ll be in touch shortly!</div>').fadeIn('fast'); });
						} else {
							$('#contact_form_container').append('<div class="warning">We\'re sorry, your contact request was unsuccessful</div>');
						}
					}  
				});
			} else {
				generate_alert('Please complete all required fields!', 'error');
			}
			return false;
			
		});
		$('[name=name]').focus(function() { 
			if($(this).val() === '* Name') { 
				$(this).val('');
			}
		}).blur(
			function() { 
				if($(this).val() === '') { $(this).val('* Name'); }
			}
		);
		$('[name=email]').focus(function() { 
			if($(this).val() === '* Email') { 
				$(this).val('');
			}  
		}).blur(
			function() { 
				if($(this).val() === '') { $(this).val('* Email'); }
			}
		);
		$('[name=phone]').focus(function() { 
			if($(this).val() === 'Phone number') { 
				$(this).val('');  
			}
		}).blur(
			function() { 
				if($(this).val() === '') { $(this).val('Phone number'); }
			}
		);		
		$('[name=message]').focus(function() { 
			if($(this).val() === '* Your message') { 
				$(this).val('');
			}
		}).blur(
			function() { 
				if($(this).val() === '') { $(this).val('* Your message'); }
			}
		);
		
		setInterval( 'slideshow_switch()', 5000 );
		
	}//end contact
	
	//extra covers
	if($('div.extra_covers_main.options').length !== 0) {
		updateFabricTotal(document.cart_multi_3);
	}
	
	//basket 
	if($('#basket_contents').length !== 0) {
		$('#basket_contents img').error(function() {
			$(this).remove();
		});
		
		$('#basket_contents a.lower').click(function(e) {
			e.preventDefault();
			var item_id = $(this).closest('div.basket_item').attr('id').replace('basket_item_', '');
			$.getJSON("basket.php?a=quantity&id=" + item_id + "&v=-1", 
				function(result) {
					if(result.response !== false) {
						basket_update_quantity(item_id, result);
					}
				}  
			);
		});
		$('#basket_contents a.increase').click(function(e) {
			e.preventDefault();
			var item_id = $(this).closest('div.basket_item').attr('id').replace('basket_item_', '');
			$.getJSON("basket.php?a=quantity&id=" + item_id + "&v=1", 
				function(result) {
					if(result.response !== false) {
						basket_update_quantity(item_id, result);
					}
				}  
			);
		});
		$('#basket_contents a.remove').click(function(e) {
			e.preventDefault();
			var item_id = $(this).closest('div.basket_item').attr('id').replace('basket_item_', '');
			$.getJSON("basket.php?a=remove&id=" + item_id, 
				function(result) {
					if(result.response !== false) {
						$('#basket_item_'+item_id).fadeOut('slow', function() { 
							$(this).remove(); 
							if($('div.basket_item').length == 0) {
								$('#basket_empty').fadeIn('slow');
								$('div.basket_extras').hide();
							}
						});
						basket_update_values(result);
					}
				}  
			);
		});
	}
		
	//assembly
	if($('#assembly_form').length !== 0) {
		$('#assembly_form').submit(function(e) {
			e.preventDefault();
			
			var postcode = $('#assembly_form [name=postcode]').val();
			if(postcode.length > 0) {
				
				$.ajax({ type: "POST", url: "inc/ajax/assembly.php", data: "postcode="+postcode,
					success: function(data) {
						var message = '';
						if(data == "1") {
							message = "Congratulations! You're eligible for &pound;45 assembly.";
						}else if(data == "2") {
							message = "Congratulations! You're eligible for &pound;60 assembly.";
						}else {
							message = "Unfortunately, you're not eligible.";
						}
						//$('#assembly_form').hide();
						$('#assembly_result').html(message).fadeIn('fast');						
					}
				});
			} else {
				generate_alert('Please enter a postcode', 'error');
			}
			return false;
		});
	}
	
	//delivery
	if($('#delivery_form').length !== 0) {
		$('#delivery_form a.calculate').click(function(e) {
			var postcode = $('#delivery_form [name=postcode]').val();
			if(postcode.length > 0) {
				$.getJSON("inc/ajax/delivery.php?p="+postcode,
					function(data) {
						var message;
						if(data !== false) {
							if(data[0] == "Free" && data[1] == "Free") {
								message  = 'Delivery will be free to this area';
							} else {
								message  = 'The surchage for orders up to a 3 seat sofa will be ' + data[0] + ' and an order bigger than this (no matter what the size or quantity) will be ' + data[1];
							} 
						}
						if(data === false) {
							message = 'The postcode you entered is not recognized. Please <a href="/contact.php" title="Contact us">contact us</a> to arrange delivery.';
						}
						$('#delivery_form').hide();
						$('#delivery_results').html(message).fadeIn('fast');
					}); 
			} else {
				generate_alert('Please enter a postcode', 'error');
			}
		});
	}
	
	//sub-nav
	$('.ddown').each(function(index,value) {
		
			$("#"+value.id).bind("click",function(event){
				event.preventDefault();
			
				if($("#subnav_container").css("display") == "none")//sub-nav closed -> open nav 
				{
					$('.sub_nav').each(function(index,value)
					{
						$("#"+value.id).css("display","none");
					});
					$("#"+value.id).css("background-position","right -40px").parent().addClass('selected');
					$("#sub_"+value.id).css("display","block");
					$("#subnav_container").slideToggle("normal");
				}
				else if($("#subnav_container").css("display") == "block")//sub-nav open -> close nav or switch content
				{
					if($("#sub_"+value.id).css("display") == "block")//slide up
					{
						$('.ddown').each(function(index,value)
						{
							$("#"+value.id).css("background-position","top right").parent().removeClass('selected');
						});
						
						$("#subnav_container").slideToggle("normal");
					}
					else //switch content
					{
						$('.sub_nav').each(function(index,value)
						{
							$("#"+value.id).css("display","none");
						});
						$('.ddown').each(function(index,value)
						{
							$("#"+value.id).css("background-position","top right").parent().removeClass('selected');
						});
						
						$("#sub_"+value.id).fadeIn('fast');
						$("#"+value.id).css("background-position","right -40px").parent().addClass('selected');
					}
				}
				
			});
	});//end drop down menu

	//product page
	$('div.product_main a.find_out_more').click(function(e) {
		e.preventDefault();
		$(this).parent().next().toggle();
	});
	
	$('div.product_main p.price').html('&pound;' + calculatePrice());
	if($('div.product_main').length !== 0) {
		$('select').bind("change keyup", function() {
			$(this).prev('img').attr('src', '/images/options/' + $(this).val() + '.jpg');
			//new_price = calculatePrice();
			//$('p.price').html('&pound;' + new_price);
		});
		
		$('select').each(function(i) {
			var value = $(this).val();
			$(this).prev('img').attr('src', '/images/options/' + value + '.jpg');
		});
		
		if($('select[name=option[2]]').length !== 0) {
			$('select[name=option[2]]').change(function() {
				$.getJSON("inc/ajax/delivery_date.php?id="+$(this).val(),
					function(data) { 
						if(data !== false) {
							$('#earliest_delivery_date').fadeOut('fast', function() { $(this).html(data).fadeIn('fast'); });
							$('#earliest_delivery_date_2').fadeOut('fast', function() { $(this).html(data).fadeIn('fast'); });
						}					
					}
				);
			});
		}
		
		// product details slider
		if (($.browser.msie && $.browser.version !== '6.0') || !$.browser.msie) {
			/*var product_sidebar_top_original 	= $('#product_sidebar_contents').offset().top;
			$(window).scroll(function() {
				product_info_scroller();
			});*/
			
			// Rebind 
			$('a.lightbox_trigger').fancybox({ 
				overlayOpacity: 0.7,
				callbackOnClose: function() {
					$(window).scroll(function() {
						product_info_scroller();
					});
				}
			});
		}
		
		/*function product_info_scroller() {
			var product_sidebar_top 		= $('#product_sidebar_contents').offset().top;
			var product_sidebar_height		= $('#product_sidebar_contents').height();
			var footer_pos					= $('#footer_container').offset();
			var window_top 					= $(window).scrollTop();
	
			if(window_top <= (product_sidebar_top_original - 15)) {
				$('#product_sidebar_contents').css({'position': 'relative', 'top': '0px'});
			} else if(window_top >= (product_sidebar_top - 15)) {
				$('#product_sidebar_contents').css({'position': 'fixed', 'top': '15px', 'margin-top': '0px' });
			} 
			if((window_top + product_sidebar_height) > footer_pos.top) {
				$('#product_sidebar_contents').css({'position': 'absolute', 'top': (footer_pos.top - product_sidebar_top_original - product_sidebar_height - 1)});
			}
		}*/
	}//end product page
	
	//product category page
	if($('#price_range_slider').length !== 0) {
		var price_range_min_form = parseInt($('#price_range_min_form').val(), 10);
		var price_range_max_form = parseInt($('#price_range_max_form').val(), 10);
		$("#price_range_slider").slider({
			range: 	true,
			min: 	0,
			max: 	1000,
			step: 	25,
			values: [price_range_min_form, price_range_max_form],
			slide: function(event, ui) {
				$('#price_range_min').html('&pound;' + ui.values[0]);
				$('#price_range_max').html('&pound;' + ui.values[1] + (ui.values[1] == 1000 ? '+' : ''));
				$('#price_range_min_form').val(ui.values[0]);			
				$('#price_range_max_form').val(ui.values[1]);				
			}
		});
		$('#price_range_min').html('&pound;' + price_range_min_form);
		$('#price_range_max').html('&pound;' + price_range_max_form + (price_range_max_form == 1000 ? '+' : ''));
	}
	// end product category page
	
	// product search page
	if($('div.category_main').length !== 0) {
		$('a.lightbox').fancybox({ 
			'width'				: 700,
			'height'			: 500,
			'autoScale'     	: false,
			'transitionIn'		: 'none',
			'transitionOut'		: 'none',
			'type'				: 'iframe',
			'scrolling' 		: 'no'
		});
		$('a.filter_toggle').click(function(e) {
			e.preventDefault();
			$('#category_search').toggle();
		});
		$('a#sofabed_info').click(function(e) {
			e.preventDefault();
			$("#sofabed_info_content").fadeIn('fast');
			$.scrollTo("#sofabed_info_content", 500);			
		});
		$('a.close').click(function(e) {
			e.preventDefault();
			$('#sofabed_info_content').fadeOut('fast');
			$.scrollTo('#category_search', 500);
		});
	}
	// end product search page
	
	// checkout redirect page
	if($('div.redirect_main').length !== 0) {
		$('#st_form, #gc_form').animate({ opacity: 1.0 }, 5000, function() { $(this).submit() });
	}
	// end checkout redirect page
	
	// checkout delivery page
	if($('div.checkout_delivery_main').length !== 0) {
		$("#samples-content").dialog({
			bgiframe: true,
			autoOpen: false,
			height: 300,
			width: 960,
			modal: true,
			draggable: false,
			resizable: false,
			dialogClass: 'fabric_samples_main'
		});
		$('a#samples').click(function(e) {
			e.preventDefault();
			$("#samples-content").dialog('open');
		});
		var url = window.location;  
		var anchor = url.hash;
		if(anchor == "#after_postcode") {
			var offset = $(anchor).offset();
			var offsetTop = offset.top;
			$('html, body').animate({scrollTop: offsetTop}, 0);
		}
	}
	
	// checkout summary page
	if($('div.checkout_payment_main').length !== 0) {
		$("#tcs-content").dialog({
			bgiframe: true,
			autoOpen: false,
			height: 300,
			width: 960,
			modal: true,
			draggable: false,
			resizable: false
		});
		$('a#tcs').click(function(e) {
			e.preventDefault();
			$("#tcs-content").dialog('open');
		});
		
		handleSameAsDeliveryOption();
		$('input[name=same_as_delivery]').click(function() {
			handleSameAsDeliveryOption();
		});
		$('div.address_form.shipping ul input, div.address_form.shipping ul select').keyup(function (){
			if($('input[name=same_as_delivery]:checked').length > 0) {
				var altEl = $(this).attr('name').replace('shipping_', 'billing_');
				$('[name=' + altEl + ']').val($(this).val());
			}
		});
		$('div.address_form.shipping select').live("change", function() {
			if($('input[name=same_as_delivery]:checked').length > 0) {
				$('div.address_form.shipping input, div.address_form.shipping select').each(function(i) {
					var altEl = $(this).attr('name').replace('shipping_', 'billing_');
					if(altEl.length > 0) {
						$('[name=' + altEl + ']').val($(this).val());
					}
				});
			}
		});
		$('[name=shipping_postcode]').change(function() {
			$('#delivery_options').hide().html('');
		})
		
		if($('#delivery_form').length !== 0) {
			$('#delivery_form').submit(function() {
				if($('input[name=shipping_postcode]').val().length > 0 &&
				    $('input[name=shipping_address1]').val().length > 0 &&
					$('input[name=shipping_firstname]').val().length > 0 &&
					$('input[name=shipping_lastname]').val().length > 0 &&
					$('input[name=shipping_phone]').val().length > 0 &&
					$('input[name=shipping_phone_mobile]').val().length > 0 &&
					$('input[name=shipping_email]').val().length > 0 &&
				    $('input[name=shipping_town]').val().length > 0 &&
				    $('input[name=shipping_county]').val().length > 0 &&
					(
						$('input[name=same_as_delivery]:checked').length > 0 || (
							$('input[name=billing_postcode]').val().length > 0 &&
							$('input[name=billing_address1]').val().length > 0 &&
							$('input[name=billing_firstname]').val().length > 0 &&
							$('input[name=billing_lastname]').val().length > 0 &&
							$('input[name=billing_phone]').val().length > 0 &&
							$('input[name=billing_phone_mobile]').val().length > 0 &&
							$('input[name=billing_email]').val().length > 0 &&
							$('input[name=billing_town]').val().length > 0 &&
							$('input[name=billing_county]').val().length > 0
						)
					) &&
				    $('input[name=delivery_method]:checked').length > 0 &&
					($('input[name=delivery_time]:checked').length > 0 || $('input[name=delivery_method]:checked').val() == 'free' ||
					 $('input[name=delivery_method]').val() == 'low_cost')) {
					return true;
				} else {
					$(".required").removeClass('required_invalid');
					$(".required").each(function(i) {
						if($(this).val().length == 0) {
							$(this).addClass('required_invalid');
						}
					});
					if($('input[name=delivery_method]:checked').val() != 'free' && $('input[name=delivery_method]').val() != 'low_cost') {
						generate_alert('Please select a delivery date and time', 'error');
					} else {
						generate_alert('Please complete all required fields', 'error');
					}
				}
				return false;
			});
		}
		$('#show_delivery_options').click(function() {
			if($('input[name=shipping_postcode]').val().length > 0 &&
			    $('input[name=shipping_address1]').val().length > 0 &&
				$('input[name=shipping_firstname]').val().length > 0 &&
				$('input[name=shipping_lastname]').val().length > 0 &&
				$('input[name=shipping_phone]').val().length > 0 &&
				$('input[name=shipping_phone_mobile]').val().length > 0 &&
				$('input[name=shipping_email]').val().length > 0 &&
			    $('input[name=shipping_town]').val().length > 0 &&
			    $('input[name=shipping_county]').val().length > 0 &&
				(
					$('input[name=same_as_delivery]:checked').length > 0 || (
						$('input[name=billing_postcode]').val().length > 0 &&
						$('input[name=billing_address1]').val().length > 0 &&
						$('input[name=billing_firstname]').val().length > 0 &&
						$('input[name=billing_lastname]').val().length > 0 &&
						$('input[name=billing_phone]').val().length > 0 &&
						$('input[name=billing_phone_mobile]').val().length > 0 &&
						$('input[name=billing_email]').val().length > 0 &&
						$('input[name=billing_town]').val().length > 0 &&
						$('input[name=billing_county]').val().length > 0
					)
				)) 
			{
				$(".required").removeClass('required_invalid');
				reloadDeliveryOptions();
			} else {
				$(".required").removeClass('required_invalid');
				$(".required").each(function(i) {
					if($(this).val().length == 0) {
						$(this).addClass('required_invalid');
					}
				});
				generate_alert('Please enter your delivery and billing details before continuing. Required fields highlighted in red', 'error');
			}
		});
	}
	// end checkout summary page

	//sample fabric
	if($('#fabric_samples_form').length !== 0) {
		$('div.fabric_sample_container a').click(function(e) {
			if($(this).attr('href') == "#") {
				e.preventDefault();
			}
		});
		$('#fabric_samples_form').submit(function(e) {
			if($('[name=first_name]').val().length > 0 && $('[name=surname]').val().length > 0 && 
				$('[name=address_1]').val().length > 0 && $('[name=postcode]').val().length > 0 && 
				$('[name=email]').val().length > 0) {
				return true;
			} else {
				generate_alert('Please complete all required fields!', 'error');
			}
			return false;
		});
	}
});

/*  ADH 090410 */

function validatestaff(form)
{
	retval=true;
	var dateval=form.ret_day.value;
	if(dateval && !isDate(dateval))
	{
		retval=false;
	}
	var priceval=form.ret_price.value;
	if(priceval && !isPrice(priceval))
	{
		alert("Please enter a price in the format 0.50 or 3.99 or 4.00 etc");
		retval=false;
	}
	return retval;
}

/**
 * DHTML date validation script. Courtesy of SmartWebby.com (http://www.smartwebby.com/dhtml/)
 */
// Declaring valid date character, minimum year and maximum year
var dtCh= "/";
var minYear=1900;
var maxYear=2100;

function isInteger(s){
	var i;
    for (i = 0; i < s.length; i++){   
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}

function stripCharsInBag(s, bag){
	var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++){   
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function daysInFebruary (year){
	// February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}
function DaysArray(n) {
	for (var i = 1; i <= n; i++) {
		this[i] = 31
		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
		if (i==2) {this[i] = 29}
   } 
   return this
}

function isDate(dtStr){
	var daysInMonth = DaysArray(12)
	var pos1=dtStr.indexOf(dtCh)
	var pos2=dtStr.indexOf(dtCh,pos1+1)
	var strDay=dtStr.substring(0,pos1)
	var strMonth=dtStr.substring(pos1+1,pos2)
	var strYear=dtStr.substring(pos2+1)
	strYr=strYear
	if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
	if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
	for (var i = 1; i <= 3; i++) {
		if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
	}
	month=parseInt(strMonth)
	day=parseInt(strDay)
	year=parseInt(strYr)
	if (pos1==-1 || pos2==-1){
		return false
	}
	if (strMonth.length<1 || month<1 || month>12){
		alert("Please enter a valid month")
		return false
	}
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
		alert("Please enter a valid day")
		return false
	}
	if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
		alert("Please enter a valid 4 digit year between "+minYear+" and "+maxYear)
		return false
	}
	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
		alert("Please enter a valid date")
		return false
	}
return true
}

function isPrice(numStr)
{
	matches = numStr.match(/^([1-9]{1}[0-9]{0,3}|0)\.[0-9]{2}$/g);
	for(i in matches)
	{
		if(matches[i] == numStr)
		{
			return true;
		}
	}
	return false; 
}

/*  END ADH 090410 */

function setCheckedValue(radioObj, newValue) {
	if(!radioObj)
		return;
	var radioLength = radioObj.length;
	if(radioLength == undefined) {
		radioObj.checked = (radioObj.value == newValue.toString());
		return;
	}
	for(var i = 0; i < radioLength; i++) {
		radioObj[i].checked = false;
		if(radioObj[i].value == newValue.toString()) {
			radioObj[i].checked = true;
		}
	}
}
