function isBlank( str )
{
	return String(str).replace(/\s/g, "") === "";
}

function msgBox(str)
{
	$.facebox(str);
}

function setResidential(type, checked )
{
	var e = $("#" + type + "_companyname");
	if( e ) {
		if( checked )
			e.val("residential").css('color', '#ccc');
		else
			e.val('').css('color', 'black');
		e.attr("disabled", checked);
	}
}

function enterUpdateCart( )
{
	return true;
}

function copyDelivery( booliness )
{
	var fields = ["attention", "companyname", "address1", "address2", "suburb", "state", "postcode"];
	if( booliness ) {
		for(var i in fields) {
			$("#billing_" + fields[i]).val( $("#delivery_" + fields[i]).val()).attr("disabled", true);
		}
		var country = $("#delivery_country").val();
		$("#billing_country option[value='" + country + "']").attr("selected", true);
		$("#billing_country").attr("disabled", true);
	} else {
		for(var i in fields )
			$("#billing_" + fields[i]).attr("disabled", false);
		$("#billing_country").attr("disabled", false);
	}
}

function copyOnBlur( id )
{
	return;
	if( $("#use_delivery").attr("checked") ) {
		var field = String(id).replace(/delivery_/i, '');
		$("#billing_" + field).val( $('#' + id).val() ).attr("readonly", true).addClass('disabled');
	}
}

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 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 applyMemberCode(themembercode)
{
	$.facebox("Please wait...");
	var membercode = themembercode || $("#membercode").val();
	$.post("ajax/apply-membercode.asp", { membercode: membercode }, function(xml) {
		var response = $("msg", xml).text();
		var code = Number($("code", xml).text());
		var msg = $("#membercode_msg");
		msg.text(response);
		if( code == 0 ) {
			if( themembercode !== undefined )
				location.reload();
			else {
			var img = $('image', xml).text();
			var href = "prolist.asp?categoryid=all";
			msgBox("Code accepted, please wait.");
			window.setTimeout( function() { location.href = 'prolist.asp?categoryid=all'; }, 1000);
			var invoiceoptions = $("#invoice_options");
			if( invoiceoptions.length > 0 )
				invoiceoptions.show();
			}
		} else {
			msgBox('Unfortunately your member code could not be found.');
		}
	});
}

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 activateCode()
{
	var username = $("#username").val();
	var password = $("#password").val();

	$.post("ajax/schools-login.asp", { username: username, password: password }, function(xml) {
		var response = $("response", xml).text();
		if( response == "fail" )
			$("#errormsg").text("Code cannot be verified.  Please try again or cancel to continue to shop for regular items.");
		else {
			msgBox('Access code accepted. Please wait ...');
			window.setTimeout( function() { location.href='prolist.asp?categoryid=944'; }, 1000);
		}

	});
}

function checkSignup()
{
	var email = $("#email");
	var password1 = $("#password1");
	var password2 = $("#password2");

	if( ! isEmail(email.val() ) ) {
		msgBox("In order to sign up, you must enter a valid email address.");
		email.focus();
		return false;
	}

	if( isBlank(password1.val()) ) {
		msgBox("You must choose a password.");
		password1.focus();
		return false;
	}

	if( isBlank(password2.val()) ) {
		msgBox("You must enter a confirmation password.");
		password2.focus();
		return false;
	}

	if( password1.val().length < 4 || password2.val().length < 4 ) {
		msgBox("Your password is too short. Passwords must be between 4 and 12 characters long.");
		return false;
	}

	if( password1.val().length > 12 || password2.val().length > 12) {
		msgBox("Your password is too long. Passwords must be between 4 and 12 characters long.");
		return false;
	}

	if( password1.val() != password2.val() ) {
		msgBox("Your password and confirmation passwords do not match. Please ensure that you have typed them identically.");
		password2.focus();
		return false;
	}
}

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").val();
	var subcategory = $("#subcategory").val();
	$.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);
			}
	);

	$("a[rel='facebox']").facebox();

});

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 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()
{
	$("div#creditcard-details").hide();
	$("#invoice-details").hide();
	var payoption = $("input[name='payoption']:checked");
	if( payoption.val() != "invoice" ) {
		$("div#creditcard-details").show();
		$(".creditcard_form").find("input,select").attr("disabled", false);
	} else {
		$("#invoice-details").show();
		$(".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 isPostCode( postcode )
{
	postcode = String(postcode).replace(/\s/g, '');
	if( isBlank(postcode) )
		return false;
	if( postcode.replace(/([A-Z]|[a-z]|[0-9]|-)*/i, '').length > 0 ) {
		return false;
	} else
		return true;
}

function validateShippingDetails()
{

	//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 attention = $("#delivery_attention");
	var country = $("#delivery_country");
	var companyname = $("#delivery_companyname");
	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( ! isPostCode( postcode.val() ) ) {
		msg("Please enter a valid 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 billing details
	/*
	var attention = $("#billing_attention");
	var residential = $("#billing_residential");
	var companyname = $("#billing_companyname");
	var country = $("#billing_country");
	var address = $("#billing_address1");
	var suburb = $("#billing_suburb");
	var state = $("#billing_state");
	var postcode = $("#billing_postcode");
	var email = $("#billing_email");
	
	if( isBlank(attention.val()) ) {
		msg("Please enter the billing attention.");
		return false;
	} else if( isBlank( country.val() ) ) {
		msg("Please enter the billing country.");
		country.addClass("highlighted");
		return false;
	} else if( isBlank( address.val() ) ) {
		msg("Please enter the billing address.");
		address.focus();
		return false;
	} else if( isBlank( suburb.val() ) ) {
		msg("Please enter the billing city/suburb.");
		suburb.focus();
		return false;
	} else if( isBlank( state.val() ) ) {
		msg("Please enter the billing state.");
		state.focus();
		return false;
	} else if( ! isPostCode( postcode.val() ) ) {
		msg("Please enter a valid billing post/zip code.");
		postcode.focus();
		return false;
	} else if( ! isEmail(email.val()) ) {
		msg("Please enter the billing email address.");
		email.focus();
		return false;
	}
	*/
	return true;
}

function validatePaymentDetails()
{
	var method = $("input[name='payoption']:checked");
	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;
		}
	} else if( method.val() == "invoice" ) {
		/*
		var attention = $("#billing_attention");
		var country = $("#billing_country");
		var address = $("#billing_address1");
		var suburb = $("#billing_suburb");
		var state = $("#billing_state");
		var postcode = $("#billing_postcode");
		var email = $("#billing_email");
		
		if( isBlank(attention.val()) ) {
			msg("Please enter the billing attention.");
			return false;
		} else if( isBlank( country.val() ) ) {
			msg("Please enter the billing country.");
			country.addClass("highlighted");
			return false;
		} else if( isBlank( address.val() ) ) {
			msg("Please enter the billing address.");
			address.focus();
			return false;
		} else if( isBlank( suburb.val() ) ) {
			msg("Please enter the billing city/suburb.");
			suburb.focus();
			return false;
		} else if( isBlank( state.val() ) ) {
			msg("Please enter the billing state.");
			state.focus();
			return false;
		} else if( isBlank( postcode.val() ) ) {
			msg("Please enter the billing post/zip code.");
			postcode.focus();
			return false;
		} else if( ! isEmail(email.val()) ) {
			msg("Please enter the billing email address.");
			email.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 {
		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;
}