var basketUpdateTimeout = 0;
var basketUpdating = false;
var addressDropdown;
var openProduct = 0;
var searchtimer;
jQuery.fx.interval = 50;
dayBookerShown = false;
var creditAvailable = false;
var isProcessing = false;

function slideInit(){
	//slider
	var slide = $('#slide');
	if(!slide.length){return;}
	var slide_item = slide.find('.item');
	var slide_viewport_width = slide.find('#slide_viewport').width();
	var slide_item_width = slide_item.outerWidth(true);
	var slide_scroll = $('#slide_scroll');
	var slide_scroll_width = slide_item_width*slide_item.length;
	var slide_scroll = slide_scroll.width(slide_scroll_width);
	var slide_nums = $('#slide_nums');
	var slide_count = 0;
	var lastDirection = 'left';
	
	for(var i=1,l=slide_item.length; i<=l; i++){
		slide_nums.append('<span>'+i+'</span>');
		slide_count++;
	}
	
	var slide_interval = 2500 * slide_count;
	var slide_nums_width = slide_nums.width();
	var slide_drag_percent = slide_viewport_width/slide_scroll_width;
	var slide_drag_width = slide_nums_width*slide_drag_percent;
	
	function animateLeft() {
		lastDirection = 'left';
		$('#slide_scroll').delay(4000).animate({
			left: 0 - ( $('#slide_scroll').width() - $('#slide_viewport').width() + 4 ) 
		}, slide_interval, 'linear', function(){
			animateRight();
		});
		$('#slide_drag').delay(4000).animate({
			left: 0 - ( $('#slide_drag').width() - $('#slide_nums').width() ) 
		}, slide_interval, 'linear');
	}
	
	function animateRight() {
		lastDirection = 'right';
		$('#slide_scroll').delay(4000).animate({
			left: 0 
		}, slide_interval, 'linear', function(){
			animateLeft();
		});
		$('#slide_drag').delay(4000).animate({
			left: 0 
		}, slide_interval, 'linear');
	}
	
	function justifyDragBar(){
		var cur = parseInt(slide_scroll.css('left'));
		slide_drag.css({'left':Math.abs(cur/slide_scroll_width)*slide_nums_width+'px'});
	}
	
	function justifyViewport(){
		var cur = parseInt(slide_drag.css('left'));
		slide_scroll.css({'left':'-'+Math.abs(cur/slide_nums_width)*slide_scroll_width+'px'});
	}	
	
	function scroll(dir){
		$('#slide_scroll').stop(true,false);
		$('#slide_drag').stop(true,false);
		var cur = parseInt(slide_scroll.css('left'));
		var allow_scroll_width = dir==='left' ? Math.abs(cur) : slide_scroll_width - Math.abs(cur) - slide_viewport_width;
		var scroll_width = allow_scroll_width > slide_item_width ? slide_item_width : allow_scroll_width + (dir==='right' ? 4 : 0);
		if(scroll_width===0){return;}
		if(dir==='left'){
			slide_scroll.animate({left:'+='+scroll_width+'px'}, 'fast', justifyDragBar);
		}else if(dir==='right'){
			slide_scroll.animate({left:'-='+scroll_width+'px'}, 'fast', justifyDragBar);
		}
	}
	
	if($('#slide_scroll').width() > $('#slide_viewport').width()) {
		var startX, endX, oldLeft, newLeft, that, move = false;
		var slide_drag = $('<div id="slide_drag" />').width(slide_drag_width).appendTo(slide_nums).mousedown(function(e){
			
			$('#slide_scroll').stop(true,false);
			$('#slide_drag').stop(true,false);
			
			move = true;
			startX = e.pageX;
			oldLeft = parseInt(slide_drag.css('left'));
			
			$(document).select(function(){
				return false;
			}).mousemove(function(e){
				if(!move){return;}
					newLeft = oldLeft+(e.pageX-startX);
					if(newLeft<0){
						slide_drag.css('left','0px');
					}else if(newLeft+slide_drag_width>slide_nums_width){
						slide_drag.css('left',slide_nums_width-slide_drag_width+'px');
					}else{
						slide_drag.css('left',newLeft+'px');
					}
					justifyViewport();
					return false;
			}).mouseup(function(){
				move = false;
				$(document).unbind('mousemove').unbind('mouseup').unbind('select');
			});
		});
		
		$(document).ready( function() {
			animateLeft();
		});

		slide.find('#slide_left').click(function(){
			scroll('left');
		});
		slide.find('#slide_right').click(function(){
			scroll('right');
		});	
		slide_scroll.mouseenter(function(){
			$('#slide_scroll').stop(true,false);
			$('#slide_drag').stop(true,false);
		});
		slide_scroll.mouseleave(function(){
			var totalWidth = $('#slide_scroll').width() - $('#slide_viewport').width() + 4;
			var leftPosition = 0 - $('#slide_scroll').position().left;
			if(lastDirection == 'left') {
				var percentMoved = 1 - (leftPosition / totalWidth);
				var restart_slide_interval = percentMoved * slide_interval;
				$('#slide_scroll').delay(1000).animate({
					left: 0 - ( $('#slide_scroll').width() - $('#slide_viewport').width() + 4 ) 
				}, restart_slide_interval, 'linear', function(){
					animateRight();
				});
				$('#slide_drag').delay(1000).animate({
					left: 0 - ( $('#slide_drag').width() - $('#slide_nums').width() ) 
				}, restart_slide_interval, 'linear');
			}
			else {
				var percentMoved = leftPosition / totalWidth;
				var restart_slide_interval = percentMoved * slide_interval;
				$('#slide_scroll').delay(1000).animate({
					left: 0 
				}, restart_slide_interval, 'linear', function(){
					animateLeft();
				});
				$('#slide_drag').delay(1000).animate({
					left: 0 
				}, restart_slide_interval, 'linear');
			}
		});
	}
}


function labelInit(context){
	context = context || 'body';
	$(':text, :password, textarea', context).not('.qty_text').each(function(){
		if($.trim(this.value).length){
			$('label[for="'+this.id+'"]').hide();
		}
	}).focus(function(){
		$('label[for="'+this.id+'"]').addClass('fieldLabelGrey');
	}).blur(function(){
		if(!$.trim(this.value).length){
			$('label[for="'+this.id+'"]').removeClass('fieldLabelGrey');
			$('label[for="'+this.id+'"]').show();
		}
	}).change(function(){
		if($.trim(this.value).length){
			$('label[for="'+this.id+'"]').hide();
		}
		else {
			$('label[for="'+this.id+'"]').show();
		}
	}).keyup(function(){
		if($.trim(this.value).length){
			$('label[for="'+this.id+'"]').hide();
		}
		else {
			$('label[for="'+this.id+'"]').show();
		}
	});
}

function pulseOffer() {
	$('.offer_tag').animate(
		{width:89,height:89,marginLeft:-3,marginTop:-3},500,
		function(){
			$('.offer_tag').animate({width:83,height:83,marginLeft:0,marginTop:0},500,function(){pulseOffer();});
		}
	);
}

function showDetail(productId) {
	var pagePath = $('#product_'+productId+'_link').val();
	$('#product').load(pagePath, function(){
		$('#tb_overlay').show();
		
		var windowWidth = $(window).width();
		var windowHeight = $(window).height();
		var windowScroll = $(window).scrollTop();
		var productWidth = $('#product').width();
		var productHeight = $('#product').height();
		var topPosition = ((windowHeight - productHeight) / 4) + windowScroll;
		var leftPosition = (windowWidth - productWidth) / 2;
		
		openProduct = productId;
		
		$('#product').css('top',topPosition+'px');
		$('#product').css('left',leftPosition+'px');
		$('#product').show();
	});
}
function hideDetail() {
	$('#tb_overlay').hide();
	$('#product').hide();
}

function showDeliveryInfo() {
	$('#overlay').show();
	
	var windowWidth = $(window).width();
	var windowHeight = $(window).height();
	var windowScroll = $(window).scrollTop();
	var popupWidth = $('#di_popup').width();
	var popupHeight = $('#di_popup').height();
	var topPosition = ((windowHeight - popupHeight) / 4) + windowScroll;
	var leftPosition = (windowWidth - popupWidth) / 2;
	
	$('#di_popup').css('top',topPosition+'px');
	$('#di_popup').css('left',leftPosition+'px');
	$('#di_popup').show();
}
function hideDeliveryInfo() {
	$('#overlay').hide();
	$('#di_popup').hide();
}

function showDeliveryCheck() {
	var validate = new validateForm();
	validate.validatePostCode('check_pc','Invalid Postcode');
	
	if( validate.numberOfErrors() > 0 ) {
		validate.displayErrors();
	} else {
		var postcodeToCheck = $('#check_pc').val();
		var checkURL = '/delivery_check?postcode='+encodeURI(postcodeToCheck);
		$('#dc_popup').load(checkURL, function(){
			$('#overlay').show();
			
			var windowWidth = $(window).width();
			var windowHeight = $(window).height();
			var windowScroll = $(window).scrollTop();
			var popupWidth = $('#dc_popup').width();
			var popupHeight = $('#dc_popup').height();
			var topPosition = ((windowHeight - popupHeight) / 4) + windowScroll;
			var leftPosition = (windowWidth - popupWidth) / 2;
			
			$('#dc_popup').css('top',topPosition+'px');
			$('#dc_popup').css('left',leftPosition+'px');
			$('#dc_popup').show();
		});
	}
	return false;
}
function hideDeliveryCheck() {
	$('#overlay').hide();
	$('#dc_popup').hide();
}

function detailExpand(showOnly) {
	if(typeof(showOnly) == 'undefined') {
		showOnly = false;
	}
	if(showOnly) {
		if(!($('#detailExpander').parent().next('dl:visible').length)) {
			$('#detailExpander').toggleClass("shrink"); 																			 
			$('#detailExpander').parent().next('dl').slideToggle("fast");
		}
	}
	else {
		$('#detailExpander').toggleClass("shrink"); 																			 
		$('#detailExpander').parent().next('dl').slideToggle("fast");
	}
}

function detailShrink() {
	$('#detailExpander').toggleClass("shrink"); 
	$('#detailShrinker').parent().parent().slideToggle("fast");
}

function qtyAdd(elementId) {
	var mun=parseInt($('#'+elementId).val())+1;
	$('#'+elementId).val(mun);
}

function qtyCut(elementId) {
	var mun=parseInt($('#'+elementId).val())-1;
	if(mun>=0) $('#'+elementId).val(mun);
}

function qtyAddBasket(elementId) {
	basketUpdating = true;
	clearTimeout(basketUpdateTimeout);
	var mun=parseInt($('#CMSCatalogueBasket_basketQuantity_'+elementId).val())+1;
	$('#CMSCatalogueBasket_basketQuantity_'+elementId).val(mun);
	basketUpdateTimeout = setTimeout(updateBasket,1200);
}

function qtyCutBasket(elementId) {
	basketUpdating = true;
	clearTimeout(basketUpdateTimeout);
	var mun=parseInt($('#CMSCatalogueBasket_basketQuantity_'+elementId).val())-1;
	if(mun>=0) $('#CMSCatalogueBasket_basketQuantity_'+elementId).val(mun);
	basketUpdateTimeout = setTimeout(updateBasket,1200);
}
function removeItem(elementId) {
	clearTimeout(basketUpdateTimeout);
	$('#CMSCatalogueBasket_basketQuantity_'+elementId).val(0);
	updateBasket();
}

function qtyAddDelay(elementId) {
	clearTimeout(basketUpdateTimeout);
	var mun=parseInt($('#'+elementId).val())+1;
	$('#'+elementId).val(mun);
	basketUpdateTimeout = setTimeout(qtyUpdate,1200,false);
}

function qtyCutDelay(elementId) {
	clearTimeout(basketUpdateTimeout);
	var mun=parseInt($('#'+elementId).val())-1;
	if(mun>=0) $('#'+elementId).val(mun);
	basketUpdateTimeout = setTimeout(qtyUpdate,1200,false);
}

function qtyUpdateDelay(elementId) {
	clearTimeout(basketUpdateTimeout);
	basketUpdateTimeout = setTimeout(qtyUpdate,1200,false);
}

function qtyUpdate(elementId) {
	clearTimeout(basketUpdateTimeout);
	if( elementId != false ) {
		$('#'+elementId).val(0);
	}
	$.post( '/manage_basket.php?CMSCatalogueBasket[remove_from_cart]=1', $("#miniBasketForm").serialize(),
		function( data ){
			// scroll to the top of the window
			window.scrollTo( 0, 0 );
			// update the basket contents
			$('#basketContainer').html( data );
			labelInit('#basketContainer');
			$('#basketTotalBox').html($('#basketTotalHidden').html());
			afterUpdate();
		}
		, 'html'
	);
}

function updateBasketAfterDelay() {
	basketUpdating = true;
	clearTimeout(basketUpdateTimeout);
	basketUpdateTimeout = setTimeout(updateBasket,1200);
}

function updateBasket() {
	$('#basketForm').submit();
}

function emptyBasket() {
	if(confirm('Are you sure you want to empty your basket?')) {
		$.post( '/manage_basket.php?CMSCatalogueBasket[remove_from_cart]=1', $("#emptyBasketForm").serialize(),
			function( data ){
				// scroll to the top of the window
				window.scrollTo( 0, 0 );
				// update the basket contents
				$('#basketContainer').html( data );
				labelInit('#basketContainer');
				$('#basketTotalBox').html($('#basketTotalHidden').html());
				afterUpdate();
			}
			, 'html'
		);
	}
}

function addToBasket( id ) {
	var productFormName = 'productForm';
	var productQtyName = 'detailQty';
	if( typeof id != 'undefined' ) {
		// product section addtobasket
		productFormName = 'productForm_' + id;
		productQtyName = 'productQty_' + id;
	}
	var thisQuantity = $('#'+productQtyName).val();
	if(thisQuantity == '' || thisQuantity == 0 || !isNumber(thisQuantity)) {
		alert('Invalid quantity!');
	}
	else {
		$.post( '/manage_basket.php', $('#' + productFormName ).serialize(),
			function( data ){
				if ( data.substr( 0, 6 ) == 'ERROR:' ) {
					alert( data.substr( 6 ) );
					return false;
				}
				// scroll to the top of the window
				window.scrollTo( 0, 0 );
				// update the basket contents
				$('#basketContainer').html( data );
				labelInit('#basketContainer');
				$('#basketTotalBox').html($('#basketTotalHidden').html());
				//hideDetail();
				if(productFormName == 'productForm') {
					$('#product').hide();
					$('#tb_overlay').hide();
					console.log(openProduct);
					$('#expand_'+openProduct).click();
				}
				else {
					if(!($('#'+productFormName).parent().next(':visible').length)) {
						$('#'+productFormName).prev().find('.expand').click();
					}
				}
				afterUpdate();
			}
			, 'html' 
		);
	}
	return false;
}

function syncAddresses(clearFields) {
	if($('#my:checked').length) {
		$('#pc2').focus();
		$('#pc2').val($('#pc').val());
		$('#pc2').keyup();
		$('#pc2').blur();
		
		$('#lu2').empty();
		$('#lu1 option').clone().appendTo('#lu2');
		$('#lu2').attr('selectedIndex',$('#lu1').attr('selectedIndex'));
		
		$('#bnn2').focus();
		$('#bnn2').val($('#bnn').val());
		$('#bnn2').keyup();
		$('#bnn2').blur();
		$('#sname2').focus();
		$('#sname2').val($('#sname').val());
		$('#sname2').keyup();
		$('#sname2').blur();
		$('#tc2').focus();
		$('#tc2').val($('#tc').val());
		$('#tc2').keyup();
		$('#tc2').blur();
		$('#ct2').focus();
		$('#ct2').val($('#ct').val());
		$('#ct2').keyup();
		$('#ct2').blur();
	}
	else {
		if(clearFields) {
			$('#pc2').focus();
			$('#pc2').val('');
			$('#pc2').blur();
			
			$('#lu2').empty();
			$('#lu2').append(new Option('- Search for your postcode above...', ''));
			
			$('#bnn2').focus();
			$('#bnn2').val('');
			$('#bnn2').blur();
			$('#sname2').focus();
			$('#sname2').val('');
			$('#sname2').blur();
			$('#tc2').focus();
			$('#tc2').val('');
			$('#tc2').blur();
			$('#ct2').focus();
			$('#ct2').val('');
			$('#ct2').blur();
		}
	}
}

function resetDropdown() {
	if($('#my:checked').length) {
		$('#my').attr('checked', false);
	}
}

function checkRegisterForm() {
	var validate = new validateForm();
	
	validate.checkText('fn','First Name');
	validate.checkText('ln','Last Name');
	validate.checkText('cn','Contact Number');
	validate.checkText('mn','Mobile Number');
	validate.validateEmailAddress('ea','Email Address');
	var email1 = $('#ea').val();
	var email2 = $('#ea2').val();
	if(email1 != email2) {
		validate.addCustomError('Email Addresses do not match!');
	}
	validate.checkText('psw','Password');
	var password1 = $('#psw').val();
	var password2 = $('#cpsw').val();
	if(password1 != password2) {
		validate.addCustomError('Passwords do not match!');
	}

	validate.checkText('bnn','Delivery Address Line 1');
	validate.checkText('tc','Delivery Town or City');
	validate.checkText('bnn2','Billing Address Line 1');
	validate.checkText('tc2','Billing Town or City');
	
	validate.checkSelect('bt','','Business Type');
	validate.checkSelect('tf','','Trading From');
	validate.checkSelect('tt','','Trading To');
	
	if(document.getElementById('ta').value == 'yes') {
		validate.checkText('an','Account Number');
	}
	
	if(validate.numberOfErrors() > 0) {
		validate.displayErrors();
		return false;
	} 
	else {
		$('#registerForm').submit();
		return false;
	}
}

function checkDetailsForm() {
	var validate = new validateForm();
	
	validate.checkText('fn','First Name');
	validate.checkText('ln','Last Name');
	validate.checkText('cn','Contact Number');
	validate.checkText('mn','Mobile Number');
	validate.validateEmailAddress('ea','Email Address');
	var email1 = $('#ea').val();
	var email2 = $('#ea2').val();
	if(email1 != email2) {
		validate.addCustomError('Email Addresses do not match!');
	}
	var password1 = $('#psw').val();
	var password2 = $('#cpsw').val();
	if(password1 != password2) {
		validate.addCustomError('Passwords do not match!');
	}

	validate.checkText('bnn','Billing Address Line 1');
	validate.checkText('tc','Billing Town or City');
	
	validate.checkSelect('bt','','Business Type');
	
	if(validate.numberOfErrors() > 0) {
		validate.displayErrors();
		return false;
	} 
	else {
		$('#detailsForm').submit();
		return false;
	}
}

function logout() {
	$('#logoutForm').submit();
}

function showContent(sectionName) {
	$('.my_account_tab').removeClass('cutter');
	$('#'+sectionName+'_tab').addClass('cutter');
	$('.my_account_content').hide();
	$('#'+sectionName+'_content').show();
}

function saveAddress(addressId) {
	var realAddressId = $('#id_'+addressId).val();

	var validate = new validateForm();
	validate.checkText( 'nn_'+realAddressId, 'Address Nickname' );
	validate.checkText( 'bnn_'+realAddressId, 'Address Line 1' );
	validate.checkText( 'tc_'+realAddressId, 'Town or City' );
	if( validate.numberOfErrors() > 0 ) {
		validate.displayErrors();
		return false;
	}
	
	//Send the address for update
	var sUrl = "/xmlservice.php?service=updateDeliveryAddress";
	sUrl += '&name='+escape( $('#nn_'+addressId).val() );
	sUrl += '&address1='+escape( $('#bnn_'+addressId).val() );
	sUrl += '&address2='+escape( $('#sname_'+addressId).val() );
	sUrl += '&town='+escape( $('#tc_'+addressId).val() );
	sUrl += '&county='+escape( $('#ct_'+addressId).val() );
	sUrl += '&postcode='+escape( $('#pc_'+addressId).val() );
	sUrl += '&country=GB';
	sUrl += '&default='+escape( $('#def_'+addressId).val() );
	if( realAddressId != '0' ){ 
		sUrl += '&id='+realAddressId;
	}
	
	//Ajax stuffs
	$.ajax({
		type: "GET",
		url: sUrl,
		success: function( result ){
			if(result.ResultSet.Result[0]['result'] == 'success') {
				var savedAddressId = result.ResultSet.Result[0]['record']['id'];
				$('#id_'+addressId).val(savedAddressId);
				alert('Address saved successfully');
			}
			else {
				alert( 'Sorry, an error occured whilst saving this address.' );
			}
		},
		error : function( result ){
			alert( 'Sorry, an error occured whilst saving this address.' );
		},
		dataType: "json"
	});
}

function deleteAddress(addressId) {
	var realAddressId = $('#id_'+addressId).val();
	doDelete = true;
	if(realAddressId != 0) {
		if(confirm('Are you sure you want to remove this address?')) {
			//Ajax stuffs
			var sUrl = "/xmlservice.php?service=deleteDeliveryAddress";
			sUrl += '&id='+realAddressId;
			$.ajax({
				type: "GET",
				url: sUrl,
				success: function( result ) {
					if(result.ResultSet.Result[0]['result'] == 'success') {
						$('#id_'+addressId).parent().remove();
						alert( 'Address deleted successfully' );
					}
					else {
						alert( 'Sorry, an error occured whilst deleting this address.' );
					}
				},
				error: function( result ) {
					alert( 'Sorry, an error occured whilst deleting this address.' );
				},
				dataType: "json"
			});
		}
	}
	else {
		$('#id_'+addressId).parent().remove();
	}
}

function updateDOB() {
	var dobday = $('#dobday').val();
	var dobmonth = $('#dobmonth').val();
	var dobyear = $('#dobyear').val();
	
	if(dobday != '' && dobmonth != '' && dobyear != '') {
		var dobString = dobday + '/' + dobmonth + '/' + dobyear;
		$('#dob').val(dobString);
	}
}

function doFullSearch() {
	var searchText = $('#search').val();
	document.location = '/products/ search::'+searchText;
}

function doSubmit(element,evt) {
	var charCode = (evt.which) ? evt.which : window.event.keyCode; 
    if (charCode == 13) 
    { 
        $(element).closest('form').submit(); 
    } 
}

function isNumber(n) {
	return !isNaN(parseFloat(n)) && isFinite(n);
}

function changePaymentMethod() {
	disableButtons();
	isProcessing = true;
	$('#basketForm').submit();
}

function confirmOrder() {
	var currentNotes = $('#CMSCatalogueProcessOrder_orderDetail_notes').val();
	if(currentNotes.indexOf("(") == -1) {
		currentNotes += ' ' + deliveryTimes;
		$('#CMSCatalogueProcessOrder_orderDetail_notes').val(currentNotes);
	}
	checkBasket();
}

function checkBasket() {
	var invalidQuantities = 0;
	var validate = new validateForm();
	
	$('.basketQuantity').each(function() {
		var thisQuantity = $(this).val();
		if(thisQuantity == '' || thisQuantity == 0 || !isNumber(thisQuantity)) {
			invalidQuantities++;
		}
	});
	
	if( invalidQuantities > 0 ) {
		validate.addCustomError('Invalid quantity entered');
	}
	if(basketUpdating) {
		validate.addCustomError('Basket is updating');
	}
	
	validate.checkText('paymentMethodConfirm','Payment Method');
	
	
	if( validate.numberOfErrors() > 0 ) {
		validate.displayErrors();
	} else {
		disableButtons();
		if(!isProcessing) {
			$('#basketForm').attr('action','/redirect.php?uri=order_confirmation');
			$('#basketForm').submit();
		}
		isProcessing = true;
	}
}

function disableButtons() {
	$('#cardButton').removeClass('small_red_btn').addClass('small_grey_btn');
	$('#cashButton').removeClass('small_red_btn').addClass('small_grey_btn');
	$('#payButton').removeClass('small_red_btn').addClass('small_grey_btn');
}

function lookupPostcode( postcodeId, dropdownId, address1Id, address2Id, townId, countyId, doSync ) {
	var postcodeBox = $( '#'+postcodeId );
	var dropdown = $( '#'+dropdownId );
	var dropdownEL = document.getElementById(dropdownId);
	var postcode = postcodeBox.val();
	var sUrl = "/xmlservice.php?service=postcodeLookup&postcode="+escape(postcode);
	dropdown.empty();
	dropdownEL.options.add(new Option('- Searching...', ''));
	
	$.ajax({
		url: sUrl,
		success: function(data) {
			if(data.ResultSet.Result.message !== undefined) {
				alert('Error: '+ data.ResultSet.Result.message);
			}
			else {
				dropdown.empty();
				dropdownEL.options.add(new Option('- Select an address from the list...', ''));
				for( i in data.ResultSet.Result ) {
					if(data.ResultSet.Result[i].description) {
						dropdownEL.options.add(new Option(data.ResultSet.Result[i].description,data.ResultSet.Result[i].id));
					}
				}
				if(doSync) {
					syncAddresses(false);
				}
			}
			dropdown.parent().addClass('select_field_highlight');
		},
		error: function() {
			alert('Error looking up postcode!');
			lookupAddress( -1, dropdownId, address1Id, address2Id, townId, countyId, postcodeId, doSync );
		},
		dataType: 'json'
	});
}

function lookupAddress( addressId, postcodeId , dropdownId, address1Id, address2Id, townId, countyId, doSync ) {
	var dropdown = $( '#'+dropdownId );
	
	dropdown.parent().removeClass('select_field_highlight');
	
	var address1 = $( '#'+address1Id );
	var address2 = $( '#'+address2Id );
	var town     = $( '#'+townId );
	var county   = $( '#'+countyId );
	var postcode = $( '#'+postcodeId );
	
	if( addressId == -1 ) {
		//It's an unknown address or error
		address1.val('');
		address2.val('');
		town.val('');
		county.val('');
		address1.focus().blur();
		address2.focus().blur();
		town.focus().blur();
		county.focus().blur();
		return;
	}
	
	var sUrl = "/xmlservice.php?service=addressLookup&addressId="+escape(addressId);
	
	$.ajax({
		url: sUrl,
		success: function(data) {
			if(data.ResultSet.Result.message !== undefined) {
				alert('Error: '+ data.ResultSet.Result.message);
			}
			else {
				if( data.ResultSet.Result.length > 0 ) {
					var address = data.ResultSet.Result[0];
					address1.val(address['line1']);
					address2.val(address['line2']);
					if( address['line3'] )
						address2.val(address2.val() += ', '+address['line3']);
					if( address['line4'] )
						address2.val(address2.val() += ', '+address['line4']);
					town.val(address['post_town']);
					county.val(address['county']);
					address1.keyup();
					address2.keyup();
					town.keyup();
					county.keyup();
					if(doSync) {
						syncAddresses(false);
					}
				}
			}
		},
		error: function() {
			alert( 'Error looking up address!' );
		},
		dataType: 'json'
	});
}

function lookupLocationPostcode() {
	var validate = new validateForm();
	validate.validatePostCode('location_postcode','Postcode is invalid!');
	if( validate.numberOfErrors() > 0 ) {
		validate.displayErrors();
	}
	else {
		qtyUpdate();
	}
}

function showThisWeek() {
	$('#this_week').show();
	$('.btn_tweek').addClass('cutter');
	$('#next_week').hide();
	$('.btn_nweek').removeClass('cutter');
}

function showNextWeek() {
	$('#next_week').show();
	$('.btn_nweek').addClass('cutter');
	$('#this_week').hide();
	$('.btn_tweek').removeClass('cutter');
}

function selectDay(element,text) {
	$('.available').removeClass('chosen');
	$(element).addClass('chosen');
	$('#chosenDate').text(text);
}

function confirmBooking() {
	var chosenDate = $('#chosenDate').text();
	var sUrl = "/xmlservice.php?service=customService&customService=chooseDeliverySlot&chosenDate="+escape(chosenDate);
	
	$.ajax({
		url: sUrl,
		success: function(data) {
			if(data == 'success') {
				$('#tb_overlay').addClass('hide');
				$('#day_booker').addClass('hide');
				dayBookerShown = false;
				qtyUpdate();
			}
			else {
				alert( 'Error while confirming booking, please try again.' );
			}
		},
		error: function() {
			alert( 'Error while confirming booking, please try again.' );
		}
	});
}

function changeDeliveryAddress(addressId) {
	var sUrl = "/xmlservice.php?service=customService&customService=changeDeliveryAddress&addressId="+escape(addressId);
	
	$.ajax({
		url: sUrl,
		success: function(data) {
			
			if(data == 'success') {
				qtyUpdate();
			}
			else {
				alert( 'Error while changing address!' );
			}
		},
		error: function() {
			alert( 'Error while changing address!' );
		}
	});
}

function afterUpdate() {
	//Rebind the click events for the day booker
	$('#delivery_slot').click(function(event){
		event.preventDefault();
		$('#tb_overlay').removeClass('hide');
		$('#day_booker').removeClass('hide');
		dayBookerShown = true;
	});
	$('#day_booker .btn_close').click(function(event){
		event.preventDefault();
		$('#tb_overlay').addClass('hide');
		$('#day_booker').addClass('hide');
		dayBookerShown = false;
	});
	
	if( dayBookerShown ) {
		$('#tb_overlay').removeClass('hide');
		$('#day_booker').removeClass('hide');
	}
}

function checkContactForm() {
	var validate = new validateForm();
	
	validate.checkText('cn','Name');
	validate.validateEmailAddress('ce','Email');
	validate.checkText('contactEnquiry','Enquiry');
	
	if(validate.numberOfErrors() > 0) {
		validate.displayErrors();
		return false;
	} 
	else {
		$('#contactForm').submit();
		return false;
	}
}

function goToCheckout() {
	var basketTotal = $('#basketValueHidden').text();
	var minimumOrder = $('#basketMinimumHidden').text();
	var canProceed = false;
	
	if(!isNaN(minimumOrder)) {
		if(parseFloat(minimumOrder) < parseFloat(basketTotal)) {
			canProceed = true;
		}
	}
	
	if(canProceed) {
		document.location = '/checkout';
	}
	else {
		alert('Your basket is below the minimum order value, please add more items');
	}
}

function showLogin() {
	$('#overlay').show();
	
	var windowWidth = $(window).width();
	var windowHeight = $(window).height();
	var windowScroll = $(window).scrollTop();
	var popupWidth = $('#li_popup').width();
	var popupHeight = $('#li_popup').height();
	var topPosition = ((windowHeight - popupHeight) / 4) + windowScroll;
	var leftPosition = (windowWidth - popupWidth) / 2;
	
	$('#li_popup').css('top',topPosition+'px');
	$('#li_popup').css('left',leftPosition+'px');
	$('#li_popup').show();
}
function hideLogin() {
	$('#overlay').hide();
	$('#li_popup').hide();
}
function showRegisterMessage() {
	alert('Please register an account to gain access to this area.');
}

function forceCaps(element) {
	element.value = element.value.toUpperCase();
	element.focus();
	element.value = element.value;
}

function doLookup(element, evt, postcodeId, dropdownId, address1Id, address2Id, townId, countyId, doSync) {
	var charCode = (evt.which) ? evt.which : window.event.keyCode; 
    if (charCode == 13) 
    { 
        lookupPostcode(postcodeId, dropdownId, address1Id, address2Id, townId, countyId, doSync);
    } 
}

function showImage(imageId) {
	$('#image_'+imageId).show('slow');
}
function hideImage(imageId) {
	$('#image_'+imageId).hide('slow');
}

function triggerSearch()
{
	// cancel the last search
	clearTimeout( searchtimer );
	// instead do one in 1/2 a second
	searchtimer = setTimeout( "doSearch();", 500 );
}

function doSearch()
{
	var searchText = $('#search').val();
	// ensure we have at least 3 characters
	if( searchText.length > 2 ) {
		// send the query
		var sUrl = "/xmlservice.php?service=quickSearch&query=" + searchText + "&limit=" + 20;
		$.ajax({
			type: "GET",
			url: sUrl,
			success: function( result ){
				if(result.ResultSet.Result) {
					var searchResultCount = '';
					var searchResults = '';
					if(result.ResultSet.totalResultsReturned == 0) {
						searchResultCount = 'No products found!';
						searchResults = '';
					}
					else {
						searchResultCount = 'Displaying '+result.ResultSet.totalResultsReturned+' out of '+result.ResultSet.totalResultsAvailable+' results';
						for( var product in result.ResultSet.Result ) {
							var productName = result.ResultSet.Result[product]['display'];
							searchResults += '<div class="searchResult">\
												<div class="searchResultName"><a href="/products/ search::' + result.ResultSet.Result[product]['code'] + '" title="' + productName + '">' + productName + '</a></div> \
											  </div>';
						}
					}
					$('#searchResultCount').html(searchResultCount);
					$('#searchResults').html(searchResults);
					$('#quickSearch').show();
				}
			},
			error : function( result ){
			},
			dataType: "json"
		});
	}
}

function triggerHideSearch() {
	// cancel the last search
	clearTimeout( searchtimer );
	// hide the result in 1/2 a second
	searchtimer = setTimeout( "hideSearch();", 500 );
}

function hideSearch() {
	$('#quickSearch').hide();
}

function showBox(box) {
	$('.info_box').addClass('hide');
	$('#mun li a').removeClass('cutter');
	$('#'+ box + '_box').removeClass('hide');
	$('#'+box).addClass('cutter');
}

function checkAvailableCredit() {
	var sUrl = "/xmlservice.php?service=getIntactAvailableCredit"; 
	
	$.ajax({
		type: "GET",
		url: sUrl,
		success: function( result ){
			var amount = 1000; //parseFloat(result);
			var div = document.getElementById('creditOption');
			if( amount >= amountDue ) {
				div.innerHTML = '<a href="javascript:confirmCash();" class="small_red_btn last_btn submit_btn right"><span class="fs14 w125">Pay cash on delivery</span></a>';
				creditAvailable = true;
			} else {
				div.innerHTML = 'Credit option unavailable';
				creditAvailable = false;
			}
		},
		error : function( result ){
			alert( 'There was an error while loading credit options' );
		},
		dataType: "json"
	});
}

$(function(){
	labelInit();

	//submit button
	$('.submit_btn').click(function(){
		$(this).closest('form').submit();
	});

	//checkbox
	$('.chk_field').each(function(){
		$(this).toggleClass('chosen', $(this).find('input').is(':checked'));
	}).click(function(){
		$(this).toggleClass('chosen', $(this).find('input').is(':checked'));
	});

	//home slide
	slideInit();
	
	//delivery_addresses page
	var delivery_tpl = $('#delivery_tpl');
	if(delivery_tpl.length){
		$('#add_delivery_btn').click(function(){
			//add dom
			var new_delivery = $(delivery_tpl.html().replace(/\-X\-/g, (new Date()).getTime())).insertBefore($(this).parent('.form_section'));
			//bind label action
			labelInit(new_delivery);
		});
	}
	
	//qty justify input field
	$('.qty .plus').click(function(){
		var mun=parseInt($(this).siblings('input').val())+1;
		$(this).siblings('input').val(mun);
		return false;
	});
	$('.qty .cut').click(function(){
		var mun=parseInt($(this).siblings('input').val())-1;
		if(mun>=1) $(this).siblings('input').val(mun);
		return false;
	});
	
	$('.shopping_list .expand').click(function(){
		$(this).toggleClass("shrink"); 																			 
		$(this).parent().parent().siblings('dl').slideToggle("fast");
		return false;
	});
	
	function activitiesDoor(mun, box) {
		$(mun).mousemove(function(){
			$(box).addClass('hide');
			$(mun).removeClass('cutter');
			var id = $(this).attr('id');
			$('#'+ id + '_box').removeClass('hide');
			$(this).addClass('cutter');
		});
	}
	activitiesDoor('#mun li a', '.info_box');
	
	$('#delivery_slot').click(function(event){
		event.preventDefault();
		$('#tb_overlay').removeClass('hide');
		$('#day_booker').removeClass('hide');
		dayBookerShown = true;
	});
	$('#day_booker .btn_close').click(function(event){
		event.preventDefault();
		$('#tb_overlay').addClass('hide');
		$('#day_booker').addClass('hide');
		dayBookerShown = false;
	});	
	
	$('#btn_slot_booker').click(function(event){
		event.preventDefault();
		$('#tb_overlay').removeClass('hide');
		$('#slot_booker').removeClass('hide');
	});
	$('#slot_booker .btn_close').click(function(event){
		event.preventDefault();
		$('#tb_overlay').addClass('hide');
		$('#slot_booker').addClass('hide');
	});	
	
	pulseOffer();
	
});
