function isBlank( str )
{
	return String(str).replace(/\s/g, "") === "";
}

function checkCurrentPassword(pw)
{
	$.post('ajax/checkcurrentpw.asp', { password: pw}, function(xml) {
		var status = $('status', xml).text();
		if( status.match(/success/i) ) {
			$('#password').removeClass('invalidpassword');
		}
		else {
			$('#password').addClass('invalidpassword');
		}
	});
}

function applyCoach()
{
	var coach = $("#coachcode").val();
	$("#coachwait").show();
	$.post("check-coach.asp", { coach: coach }, function(xml) {
			$("#coachwait").hide();
			if( $("status", xml).text() == 'success') {
				$.facebox("Thank you. Please wait while we apply your code.");
				setTimeout( function() { location.reload(); }, 2500 );
			} else {
				var reason = $("reason", xml).text();
				$.facebox("Your coach code could not be found. If you believe this is in error, please contact us at <a href='mailto:aoshop@tpf.com.au'>aoshop@tpf.com.au</a>");
			}
	});
}

function checkPW(which)
{
	var pw1 = $('#password1');
	var pw2 = $('#password2');

	if( which != 2 ) {
		if( isBlank(pw1.val()) || pw1.val().length < 4 || pw1.val().length > 12 ) {
			$('#password1_error').show();
		}
	}

	if( which == 2 && pw1.val() != pw2.val() )
		$('#password2_error').show();
}

function checkPasswordDetails()
{
	var pw = $('#password');
	var pw1 = $('#password1');
	var pw2 = $('#password2');

	if( isBlank(pw.val()) ) {
		msgBox('Please enter your current password.');
		return false;
	} else if( isBlank(pw1.val()) || isBlank(pw2.val()) ) {
		msgBox('Please complete the new password and confirm new password fields.');
		return false;
	} else if( pw1.val() != pw2.val() ) {
		msgBox('Your new password and the confirmation password do not match.');
		return false;
	} else if( pw1.val().length < 4 || pw1.val().length > 12 ) {
		//since pw1 == pw2 we don't have to test both pw
		msgBox('Your new password must be between 4 and 12 characters long');
		return false;
	}
	return true;
}

function msgBox(str)
{
	$.facebox(str);
}

function applyVoucher()
{
	var vouchercode = $("#vouchercode").val();
	if( ! isBlank(vouchercode) ) {
		$("#voucherwait").show();
		$.post("ajax/apply-voucher.asp", { vouchercode: vouchercode }, function(xml) {
			$("#voucherwait").hide();
			var response = $("msg", xml).text();
			var status = $("status", xml).text();			
			if( status.match(/success/i) ) {
				$("#vouchercode_msg").text( response );
				$(document).trigger("cart-update");
			} else {
				$.facebox("We could not apply the voucher because " + response);
			}
		});
	}
}

function applyMemberCode()
{
	var membercode = $("#membercode").val();
	$.post("ajax/apply-membercode.asp", { membercode: membercode }, function(xml) {
		var code = $("code", xml).text();
		if( Number(code) == 0 )
			$(document).trigger("cart-update");
		var response = $("msg", xml).text();
		$("#membercode_msg").text( response );
	});
}

function changeCurrency()
{
	var currency = $("#currency").val();

	$.post("ajax/change-currency.asp", { currency: currency }, function() {
		location.reload();
	});
}

function registerInterest(addy)
{
	if( ! isEmail(addy) )
		$.facebox("Please enter a valid email address.");
	else {

		var href = String(location.href);
		var thesplit = href.split("?");
		var proid = thesplit[1].replace(/\D/g, "");
		$.post("ajax/register-interest.asp", { proid: proid, email:addy }, function() {
			$.facebox("Thank you. We will notify you when this product becomes available for order.");
		});
	}
}

function checkOrderSubmission()
{
	return true;
	var fname = $("#delivery_fname");
	var lname = $("#delivery_lname");
	var address = $("#delivery_address1");
	var city = $("#delivery_city");
	var state = $("#delivery_state");
	var country = $("#delivery_country");
	var postcode = $("#delivery_postcode");



	if( isBlank( fname.val()) ) {
		msgBox("You must enter your first name.");
		fname.focus();
		return false;
	} else if( isBlank(lname.val()) ) {
		msgBox("You must enter your last name.");
		lname.focus();
		return false;
	} else if( isBlank(address.val()) ) {
		msgBox("You must enter your delivery address.");
		address.focus();
		return false;
	} else if( isBlank(city.val()) ) {
		msgBox("You must enter your delivery city.");
		city.focus();
		return false;
	} else if( isBlank(state.val()) ) {
		msgBox("You must enter your delivery state.");
		state.focus();
		return false;
	} else if( isBlank(country.val()) ) {
		msgBox("You must enter your delivery country.");
		country.focus();
		return false;
	} else if( isBlank(postcode.val()) ) {
		msgBox("You must enter your delivery postcode.");
		postcode.focus();
		return false;
	}

	

	return false;
}

function emailFriend( proid )
{
	$.facebox({ ajax: "ajax/emailfriend.asp?proid=" + proid});
}

function email2friend()
{
	var yourname = $("#yourname").val();
	var youremail = $("#youremail").val();
	var friendemail = $("#friendemail").val();
	var message = $("#message").val();
	var proid = $("#product_id").val();
	var details = {
		yourname: yourname,
		youremail: youremail,
		friendemail: friendemail,
		message: message,
		proid: proid
	};
	$.post("ajax/email2friend.asp", details, function() {
		$.facebox("Thank you, this product recommendation has been sent.");
	});
}

function updateCartTotal()
{
	setTimeout( function() { $("#cart-summary-total").text( $("#new-cart-total").val()); }, 300);
}

function viewCart()
{
	var categoryid = $("#categoryid");
	var subcategory = $("#subcategory");
	if( categoryid.length > 0 )
		categoryid = categoryid.val();
	else
		categoryid = '';
	if( subcategory.length > 0 )
		subcategory = subcategory.val();
	else
		subcategory = '';
	$.facebox({ ajax: "ajax/viewcart.asp" + "?categoryid=" + categoryid + "&subcategory=" + subcategory });
	updateCartTotal();
	return false;
}

function updateCart()
{
	var prodetails = $("input[name*='prodetailid_']");
	var cart = {};
	prodetails.each( function() {
		var name = $(this).attr("name");
		var qty = $(this).val();
		cart[name] = qty;
	});

	cart.action = "set-cart";
	
	$.post("ajax/processdata.asp", cart, function() {
		$(document).trigger("cart-update");
	});
}


$(document).ready( function() {
	$("#menu img").hover(
			function() {
				var img = $(this).attr("src").replace(/\.png/, "_highlight.png");
				$(this).attr("src", img);
			},
			function() {
				var img = $(this).attr("src").replace(/\_highlight.png/, ".png");
				$(this).attr("src", img);
			}
	);

	$.ajaxSetup({
		type: "post" //ie caching fix
	});
	$("a[rel='facebox']").facebox();
	/*
	if( $.browser.msie && $.browser.version.match(/6/) && $.cookie("ie6msged") != "yes" ) {
		$("#ie6msg").show();
	}
	*/
});

function hideIEMessage()
{	
	$.cookie("ie6msged", "yes");
	$("#ie6msg").fadeOut();
}

function addProduct()
{
	var products = $("input[name*='prodetail_']");
	var product = {};
	
	products.each( function() {
		//fixme, do some validation
		var prodetailid = String($(this).attr("name"));
		var qty = parseInt($(this).val()) || 0;
		product[prodetailid] = qty;
	});

	$.post("ajax/updatecart.asp", product, function(html) {
		$(document).trigger("cart-update");
	});
}

function addSubscription(prodetailid, qty, country)
{
	var product = {};
	if( parseInt(qty) > 0 ) {
		product["prodetail_" + prodetailid] = qty;
		product["country"] = country;
		$.post("ajax/updatecart.asp", product, function(html) {
			$(document).trigger("cart-update");
		});
	}
	
}

function removeItem(prodetailid)
{
	$.post("ajax/removeitem.asp", { prodetailid: prodetailid }, function(html) {
		$(document).trigger("cart-update");
	});
}

function joinMailingList()
{
	$.facebox({
		ajax: "joinmailinglist.asp"
	});
}

function signUpForNewsletters()
{
	var name = $("#mailing-list-name");
	var email = $("#mailing-list-email");

	$.post("ajax/join-mailing-list.asp", { name: name.val(), email: email.val() }, function() {
		$.facebox("Your email has been added to our mailing list.  Thank you for expressing your interest.");
	});
}

function switchPayment()
{
	if( $(this).val() == "creditcard" ) {
		$("#creditcard_details").show();
		$("#paypal_details").hide();
	} else {
		$("#paypal_details").show();
		$("#creditcard_details").hide();
		$(".creditcard_form").find("input,select").attr("disabled", true);
	}
}

function isBlank( str )
{
	return String(str).replace(/\s/g, "") == "";
}

function isEmail( addy )
{
	var emailRegex = /^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$/;
	if( isBlank(addy) || ! String(addy).match(emailRegex) )
		return false;
	else
		return true;
}

function msg(str)
{
	$.facebox(str);
}

function validateShippingDetails()
{
	/*
	var attention = $("#delivery_attention");
	var country = $("#delivery_country");
	var address = $("#delivery_address1");
	var suburb = $("#delivery_suburb");
	var state = $("#delivery_state");
	var postcode = $("#delivery_postcode");
	var phone = $("#delivery_phone");
	
	if( isBlank(attention.val()) ) {
		msg("Please enter the delivery attention.");
		attention.addClass("highlighted");
		return false;
	} else if( isBlank( country.val() ) ) {
		msg("Please enter the delivery country.");
		country.focus();
		return false;
	} else if( isBlank( address.val() ) ) {
		msg("Please enter the delivery address.");
		address.focus();
		return false;
	} else if( isBlank( suburb.val() ) ) {
		msg("Please enter the delivery city/suburb.");
		suburb.focus();
		return false;
	} else if( isBlank( state.val() ) ) {
		msg("Please enter the delivery state.");
		state.focus();
		return false;
	} else if( isBlank( postcode.val() ) ) {
		msg("Please enter the delivery post/zip code.");
		postcode.focus();
		return false;
	} else if( isBlank( phone.val() ) ) {
		msg("Please enter the delivery phone.");
		phone.focus();
		return false;
	}

	//now validate contact details

	var fname = $("#contact_fname");
	var lname = $("#contact_lname");
	var phone = $("#contact_phone");
	var email = $("#contact_email");

	if( isBlank( fname.val() ) ) {
		msg("Please enter your first name.");
		fname.focus();
		return false;
	} else if( isBlank( lname.val() ) ) {
		msg("Please enter your last name.");
		lname.focus();
		return false;
	} else if( isBlank( phone.val() ) ) {
		msg("Please enter your phone number.");
		phone.focus();
		return false;
	} else if( ! isEmail( email.val() ) ) {
		msg("Please enter your email address.");
		email.focus();
		return false;
	}

	*/
	var valid = true;
	$(".required").each( function() {
		var id = $(this).attr("id");
		var label = $("label[for='" + id + "']").text().replace(/\*/g, "").toLowerCase();			
		if( $(this).hasClass("text") ) {
			if( isBlank( $(this).val() ) ) {					
				$(this).addClass("focus");
				$.facebox("Please complete the " + label + " field.");					
				valid = false;
				return false;
			} else
				$(this).removeClass("focus");
		} else if( $(this).hasClass("email") ) {
			if( ! isEmail( $(this).val() ) ) {
				$(this).addClass("focus");
				$.facebox("Please enter a valid email for the " + label);					
				valid = false;
				return false;
			} else
				$(this).removeClass("focus");
		}
	});

	if( $("input[name=subscription_receiver]").length > 0) {
		//do validation of subscription info
		var receiver = Boolean($("#subscription_me").attr("checked")) || Boolean($("#subscriptiongiftrecipient").attr("checked"));
		if( ! receiver ) {
			msg("Please choose your subscription receiver");
			return false;
		}
		var type = Boolean($("#subscription_new").attr("checked")) || Boolean($("#subscription_renewal").attr("checked"));
		if( ! type ) {
			msg("Please choose your subscription type");
			return false;
		}
		var fields = ["receiver", "giftrecipient", "title", "fname", "lname", "address", "suburb", "state", "postcode", "country", "email"];
		for(var i in fields) {
			var el = $("input[name=subscription_" + fields[i] + "]");
			var val = el.val();
			if( isBlank(val) ) {
				var name = $("label[for=subscription_" + fields[i] + "]").text().replace(/\*/g, "").toLowerCase();
				msg("Please enter your subscriber " + name);
				el.focus();
				return false;
			}
		}

		var phones = $("#subscription_homephone").val() + $("#subscription_workphone").val();
		if( isBlank(phones) ) {
			msg("Please enter a subscriber phone number");
			return false;
		}
	}

	return valid;
}

function validate()
{
	var action = $("#action").val();
	var valid = true;
	if( action == 'shipping-details' )
		valid = validateShippingDetails();
	else if( action == 'payment-details' )
		valid = validatePaymentDetails();
	else if( action == 'review-order' )
		valid = validateOrder();
	return valid;
}

function paidByVoucher()
{
	var paid = false;
	$.ajax({
		url : "hasvoucher.asp",
		method : "POST",
		async : false,
		data : { date : new Date() },
		success : function(xml) {
			var hasvouchers = $("hasvouchers", xml).text() == "true";
			var total = parseFloat($("total", xml).text());
			if( hasvouchers && total <= 0 ) {
				paid = true;
			}
		}
	});
	return paid;
}

function validatePaymentDetails()
{
	var method = $("input[name='payoption']:checked");
	if( paidByVoucher() )
		return true;
	if( method.length == 0 ) {
		msg("Please choose a payment method.");
		return false;
	} else if( method.val() == "creditcard") {
		//credit card validation
		var cardholdername = $("#cc_cardholdername");
		var cardnumber = $("#cc_cardnumber");
		var cardtype = $("#cc_cardtype");
		var month = $("#cc_mmexp");
		var year = $("#cc_yyexp");
		var code = $("#cc_csc");

		if( isBlank( cardholdername.val() ) ) {
			cardholdername.focus();
			msg("Please enter the card holder's name.");
			return false;
		} else if( isBlank( cardnumber.val()) ) {
			msg("Please enter the card number.");
			cardnumber.focus();				
			return false;
		} else if( cardtype.val() == "none" ) {
			msg("Please choose the card type.");
			cardtype.focus();
			return false;
		} else if( month.val() == "none" ) {
			msg("Please choose the expiration month for this card.");
			month.focus();
			return false;
		}
	}

	return true;
}

function validateOrder()
{
	if( Number($("#itemcount").val()) <= 0 ) {
		$.facebox("You must add some items to your cart before checking out !");
		return false;
	} else {
		if( $("input[name='newsletter']").length > 0 ) {
			if( $("input[name='newsletter']:checked").length == 0) {
				msg("Please select whether you would like to receive promotions and newsletters.");
				return false;
			}
		}
		var cont = confirm("Are you sure you are ready to place your order?");
		if( cont ) 
			$.blockUI({message: "Please wait"});
		return cont;
	}
}

function validateForm()
{
	var action = $("#action").val().toLowerCase();
	if( action == "shipping-details" ) {
		return validateShippingDetails();
	} else if( action == "payment-details" ) {
		return validatePaymentDetails();
	} else if( action == "review-order" ) {
		return validateOrder();
	}
	return true;
}

function nextStage(xml)
{
	var url = $("url", xml).text();
	location.href = url;
}