function relative_time(time_value) {
	var values = time_value.split(" ");
	time_value = values[1] + " " + values[2] + ", " + values[5] + " " + values[3];
	var parsed_date = Date.parse(time_value);
	var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
	var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
	delta = delta + (relative_to.getTimezoneOffset() * 60);

	if (delta < 60) {
		return 'less than a minute ago';
	} else if(delta < 120) {
		return 'about a minute ago';
	} else if(delta < (60*60)) {
		return (parseInt(delta / 60)).toString() + ' minutes ago';
	} else if(delta < (120*60)) {
		return 'about an hour ago';
	} else if(delta < (24*60*60)) {
		return 'about ' + (parseInt(delta / 3600)).toString() + ' hours ago';
	} else if(delta < (48*60*60)) {
		return '1 day ago';
	} else {
		return (parseInt(delta / 86400)).toString() + ' days ago';
	}
}	

function twitterCallback2(twitters) {
	var statusHTML = [];
	for(var i = 0; i < twitters.length; i++) {
		var status = twitters[i].text.replace(/((https?|s?ftp|ssh)\:\/\/[^"\s\<\>]*[^.,;'">\:\s\<\>\)\]\!])/g, function(url) {
			return '<a href="' + url + '">' + url + '</a>';
		}).replace(/\B@([_a-z0-9]+)/ig, function(reply) {
			return '<a href="http://twitter.com/' + reply + '" target="_blank">' + reply + '</a>';
		}).replace(/\B#([_a-z0-9]+)/ig, function(hashtag) {
			return '<a href="http://twitter.com/search?q=%23' + hashtag.substr(1) + '" target="_blank">' + hashtag + '</a>';
		});
		
		var monthname = new Array("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
		var theDate = twitters[i].created_at.replace(' +0000', '') + ' +0000';
		var timestampObj = new Date(theDate);
		var timestamp = timestampObj.getDate() + ' ' + monthname[timestampObj.getMonth()];
		
		var screenName = twitters[i].user.screen_name;
		var actualName = twitters[i].user.name;
		
		statusHTML.push('<li><p class="twitterInfo">' + screenName + ' <em>' + actualName + '</em></p><p class="tweet">' + status + '</p><p class="timestamp">' + timestamp + '</p></li>');
	}
	statusHTML.push('<li class="twitterLinks"><p><a href="http://twitter.com/wandererwines/" target="_blank">View Twitter</a></p></li>');
	$('#twitterFeedList').html(statusHTML.join(''));
	$("#twitterFeedList").removeClass('loading');
}

function showWarning() {
	$('#updateCartSubmit').click();
}

$(document).ready(function() {
	$('a.popin').fancybox({
		autoScale: false
	});
	
	$('#joinNewsletterForm').validate({
		rules: {
			firstName: "required", 
			surname: "required", 
			emailAddress: {
				required: true, 
				email: true
			}
		}, 
		messages: {
			firstName: "Please enter your first name", 
			surname: "Please enter your surname", 
			emailAddress: {
				required: "Please enter your email address", 
				email: "Please make sure this is a valid email address"
			}
		}, 
		submitHandler: function() {
			var firstName = $('#firstName').val(); 
			var surname = $('#surname').val();
			var emailAddress = $('#emailAddress').val();
			
			$.ajax({
				type: "POST", 
				url: "/pages/components/joinNewsletter.php", 
				data: ({firstName: firstName, surname: surname, emailAddress: emailAddress}), 
				success: function(response) {
					if(response == "ok") {
						alert('Thanks for joining our newsletter list!');
						$('#firstName').val('');
						$('#surname').val('');
						$('#emailAddress').val('');
					}
					else {
						alert('Sorry, there is a problem with the sign up form. Please try again.');
					}
				}
			});
		}
	});
	
	/* map hover states */
	$('#hoverDixonsCreek').hover(
		function() {
			$('#map').attr('src', '/images/map_dixons_creek.gif');
		}, 
		function() {
			$('#map').attr('src', '/images/map.gif');
		}
	);
	$('#hoverTarrawarra').hover(
		function() {
			$('#map').attr('src', '/images/map_tarrawarra.gif');
		}, 
		function() {
			$('#map').attr('src', '/images/map.gif');
		}
	);
	$('#hoverYellingbo').hover(
		function() {
			$('#map').attr('src', '/images/map_yellingbo.gif');
		}, 
		function() {
			$('#map').attr('src', '/images/map.gif');
		}
	);
	$('#hoverGembrook').hover(
		function() {
			$('#map').attr('src', '/images/map_gembrook.gif');
		}, 
		function() {
			$('#map').attr('src', '/images/map.gif');
		}
	);
	$('#hoverWesburn').hover(
		function() {
			$('#map').attr('src', '/images/map_wesburn.gif');
		}, 
		function() {
			$('#map').attr('src', '/images/map.gif');
		}
	);
	
	$('#navUl').localScroll();
	$('.submitRow').localScroll();
	
	/* hover nav! */
	var nav = $("#nav");
	var topCoord = nav.offset().top;
	var leftCoord = $('#siteShell').offset().left;
	
	var topOffset = 63; 
	var maxTop = topCoord - topOffset;
	
	var theWindow = $(window);
	
	var navFixedCSS = (nav.css('position') == 'fixed');
	
	theWindow.scroll(function () {
		if(theWindow.scrollTop() > maxTop) {
			if($.browser.msie && $.browser.version == "6.0") {
				nav.css('top', theWindow.scrollTop() + topOffset);
			} 
			else if(!navFixedCSS) {
				nav.css({
					left: leftCoord,
					top: topOffset,
					position: 'fixed'
				});
				navFixedCSS = true;
			}
		} else {
			if (navFixedCSS) {
				nav.css({
					position: 'absolute',
					top: topCoord,
					left: ''
				});
				navFixedCSS = false;
			}
		}
	});

	theWindow.resize(function () {
	    leftCoord = $('#siteShell').offset().left;
	    if (navFixedCSS) {
    	    nav.css('left', leftCoord);	        
	    }
	});	
	/* end hover nav */
	
	$('.navLink').click(function() {
		$('#navUl').find('li').removeClass('selected');
		$(this).addClass('selected');
	});
	
	/*
	$('.contentBox').waypoint(function() {
		var contentBoxName = $(this).attr('id').replace('Layout', '');
		var contentBoxID = "#navLink" + contentBoxName;
		$('#navUl').find('li').removeClass('selected');
		$(contentBoxID).addClass('selected');
	});
	*/

	/*
	$('.addWine').click(function() {
		var anchorID = $(this).attr('id').replace('wine', '');
		$.ajax({
			type: "POST", 
			url: "/eway/add-to-cart.php", 
			data: ({cartaction: 'add', qty: 1, price_id: anchorID}), 
			success: function(response) {
				if(response == "ok") {
					document.location = "/order/";
				}
				else {
					alert('Sorry, there was an issue with our website add to cart functionality.\n\nIf this issue persists, please contact us and report this issue. Thank you.');
				}
			}
		});
		return false; 
	});
	*/
	
	/* user clicks on a menu link in the Order page, needs to scroll to the correct place + handle floating nav area */
	if(location.hash.length > 0) {
		var hashURL = location.hash;
		var categoryURL = hashURL.replace('#', '').replace('Nav', '');
		var liId = "#navLink" + categoryURL;

		if(categoryURL != "top") {
			var nav = $("#nav");
			var topCoord = nav.offset().top;
			var leftCoord = $('#siteShell').offset().left;
			var topOffset = 63; 

			nav.css({
				left: leftCoord,
				top: topOffset,
				position: 'fixed'
			});
		}
		
		$('#navUl').find('li').removeClass('selected');
		$(liId).addClass('selected');
	}
	
	/* checkout functionality */
	$('#shippingDifferent-yes').click(function() {
		$('.shippingDetails').show();
	});
	$('#shippingDifferent-no').click(function() {
		$('.shippingDetails').hide();
	});
	$('#paymentOption-creditCard').click(function() {
		$('.eftDetails').hide();
		$('.creditCardDetails').show();
	});
	$('#paymentOption-eft').click(function() {
		$('.creditCardDetails').hide();
		$('.eftDetails').show();
	});
	
	$('#yourDetails').validate({
		rules: {
			billingTitle: 'required', 
			billingFirstName: 'required', 
			billingLastName: 'required', 
			billingAddress: 'required', 
			billingSuburb: 'required', 
			billingPostcode: 'required', 
			billingState: 'required', 
			billingEmail: {
				required: true, 
				email: true
			}, 
			over18: 'required', 
			shippingTitle: { required: "#shippingDifferent-yes:checked" }, 
			shippingFirstName: { required: "#shippingDifferent-yes:checked" }, 
			shippingLastName: { required: "#shippingDifferent-yes:checked" }, 
			shippingAddress: { required: "#shippingDifferent-yes:checked" }, 
			shippingSuburb: { required: "#shippingDifferent-yes:checked" }, 
			shippingPostcode: { required: "#shippingDifferent-yes:checked" }, 
			shippingState: { required: "#shippingDifferent-yes:checked" }, 
			ccType: { required: "#paymentOption-creditCard:checked" }, 
			ccName: { required: "#paymentOption-creditCard:checked" }, 
			ccNumber: {
				required: "#paymentOption-creditCard:checked", 
				creditcard: true
			}, 
			ccCCV: { 
				required: "#paymentOption-creditCard:checked", 
				minlength: 3, 
				maxlength: 4, 
				number: true
			}, 
			ccExpiryMonth: { required: "#paymentOption-creditCard:checked" }, 
			ccExpiryYear: { required: "#paymentOption-creditCard:checked" }
		}, 
		messages: {
			billingTitle: 'Please select your title', 
			billingFirstName: 'Please enter your first name', 
			billingLastName: 'Please enter your last name', 
			billingAddress: 'Please enter your address', 
			billingSuburb: 'Please enter your suburb', 
			billingPostcode: 'Please enter your postcode', 
			billingState: 'Please enter your state', 
			billingEmail: {
				required: 'Please enter your email address', 
				email: 'Please make sure your email address is a valid one'
			}, 
			over18: 'You need to be over 18 to purchase wine from The Wanderer', 
			shippingTitle: 'Please select your title', 
			shippingFirstName: 'Please enter your first name', 
			shippingLastName: 'Please enter your last name', 
			shippingAddress: 'Please enter your address', 
			shippingSuburb: 'Please enter your suburb', 
			shippingPostcode: 'Please enter your postcode', 
			shippingState: 'Please enter your state', 
			ccType: 'Please select your credit card type', 
			ccName: 'Please enter the name as printed on your credit card', 
			ccNumber: {
				required: 'Please enter your credit card number', 
				creditcard: 'Please make sure your credit card number is a valid one'
			},
			ccCCV: {
				required: 'Please enter your CCV',
				minlength: 'Your CCV needs to be 3 digits long', 
				maxlength: 'Your CCV needs to be 3 digits long', 
				number: 'Your CCV needs to be 3 digits long'
			}, 
			ccExpiryMonth: 'Please select the expiry month', 
			ccExpiryYear: 'Please select the expiry year'
		}, 
		submitHandler: function(form) {
			// lock down submit buttons
			var submitButtons = $('.submitRow input.submit');
			submitButtons.attr('disabled', true);
			
			var formFields = $(form).serializeArray();
			$.ajax({
				url: '/eway/processOrder.php', 
				type: 'POST', 
				dataType: 'json', 
				data: formFields, 
				success: function(data) {
					if(data.status == "error") {
						alert('Sorry, there was an error with your form submission. Please try again.\nYour credit card has NOT been charged.');
						submitButtons.attr('disabled', false);
					}
					else if(data.status == "invalid") {
						alert('There is an error with your entered information: \n' + data.errorMessage);
						submitButtons.attr('disabled', false);
					}
					else {
						window.location = "/confirm/";
					}
				}
			});
		}
	});
	
	$('#freightList').change(function() {
		var freightState = $(this).val();
		$.ajax({
			type: 'POST', 
			url: '/pages/components/update_freight.php', 
			dataType: 'json', 
			data: ({ freightState: freightState }), 
			success: function(response) {
				if(response.status == "ok") {
					var cartTotal = response.cartTotal;
					var freightCost = response.freightCost;
					$('#cartTotal').html('$' + cartTotal);
					$('#freightTotal').html('$' + freightCost);
					$('#paymentDetailsTotal').html('$' + cartTotal);
					
					// update the details form
					var shippingDetailsSelect = $('#shippingDifferent-yes:checked').val();
					if(shippingDetailsSelect == "Yes") {
						// shipping details are different from billing details
						$('#shippingState').val(response.freightState);
					}
					else {
						$('#billingState').val(response.freightState);
						$('#shippingState').val(response.freightState);
					}
				}
				else {
					alert('There was an error processing your request.\n' + response.message + '\nIf this error persists, please contact us.');
				}
			}
		});
	});
	
	$('#shippingState').change(function() {
		var changeState = $(this).val();
		$.ajax({
			type: 'POST', 
			url: '/pages/components/update_freight.php', 
			dataType: 'json', 
			data: ({ freightState: changeState }), 
			success: function(response) {
				if(response.status == "ok") {
					var cartTotal = response.cartTotal;
					var freightCost = response.freightCost;
					$('#cartTotal').html('$' + cartTotal);
					$('#freightTotal').html('$' + freightCost);
					$('#paymentDetailsTotal').html('$' + cartTotal);
					$('#freightList').val(response.freightState);
				}
				else {
					alert('There was an error processing your request.\n' + response.message + '\nIf this error persists, please contact us.');
				}
			}
		});
	});
	
	$('#billingState').change(function() {
		var changeState = $(this).val();
		var shippingDetailsSelect = $('#shippingDifferent-no:checked').val();
		if(shippingDetailsSelect == 'No') {
			$.ajax({
				type: 'POST', 
				url: '/pages/components/update_freight.php', 
				dataType: 'json', 
				data: ({ freightState: changeState }), 
				success: function(response) {
					if(response.status == "ok") {
						var cartTotal = response.cartTotal;
						var freightCost = response.freightCost;
						$('#cartTotal').html('$' + cartTotal);
						$('#freightTotal').html('$' + freightCost);
						$('#paymentDetailsTotal').html('$' + cartTotal);
						$('#freightList').val(response.freightState);
					}
					else {
						alert('There was an error processing your request.\n' + response.message + '\nIf this error persists, please contact us.');
					}
				}
			});
		}
	});
});
